14

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?

16

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.

  • You can use the above answer for designing a wrapping script. The new script should listen to parameters and call the old command with the method above. – Walter A May 22 '15 at 21:29
  • Also known as a HERE document, for more information you might try Wikipedia here document definition – OldTimer Jun 6 '15 at 20:12
15

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.

  • Thank you for your answer. Since my needs are very low, Expect is overkill in my case. Bjorns answer perfectly suits my needs. But I'd suggest to keep your answer for others that are in need of a more complex solution. – tmuecksch May 20 '15 at 20:35
  • +1 because I didn't know autoexpect existed and had figured that the expect learning curve was too steep for me to bother with. I'll take another look. – Joe May 23 '15 at 2:05
7

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
  • 3
    A common though ironic usage is yes n, for example: yes n | mv -i * somewhere/ – Sam Watkins May 21 '15 at 8:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.