Prepare answers for questions of a command

Let’s say I want to write a shell script that executes just one command. But this command is poorly designed. It doesn’t offer any command line options; instead it asks some questions and waits for user input.

Is there a way to prepare this input in the script, so the questions are answered automatically?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If the command is not very picky it should work with something like this:

command > /dev/null << EOF
<answer 1>
<answer 2>
<answer 3>
EOF

This requires that you know the exact answers beforehand.

Method 2

Expect can do that. From the Expect website:

Expect is a tool for automating interactive applications such as telnet, ftp, passwd, fsck, rlogin, tip, etc. Expect really makes this stuff trivial. Expect is also useful for testing these same applications […]”

It comes with a lot of help, like autoexpect.

Again from the Expect website,

autoexpect watches you interacting with another program and creates an Expect script that reproduces your interactions. For straightline scripts, autoexpect saves substantial time over writing scripts by hand.

Method 3

If your script expects one prompt answered, or several prompts in which you can give the same answer, there’s yes:

NAME
       yes - output a string repeatedly until killed

SYNOPSIS
       yes [STRING]...
       yes OPTION

DESCRIPTION
       Repeatedly output a line with all specified STRING(s), or `y'.

Use it like this:

yes Me | give_a_hug.sh


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x