Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script - Auto fill answer

Tags:

linux

bash

shell

sh

I have a bash script that has several questions, is it possible to automatically fill the answers ?

./script.sh install 

answers in order y 2 1 n n

How can I do that in bash ?

edit: is it possible to only pass the first answer ?

echo "y" | install 

and let the choice to the user to answer the next questions ?

like image 213
super trainee Avatar asked May 31 '15 23:05

super trainee


2 Answers

I would pass a here document to stdin:

./script.sh install <<EOF
y
2
1
n
n
EOF

If you want it on one line, you can also use echo:

echo -e "y\n2\n1\nn\nn" | ./script.sh install

However, I prefer the here document solution since it is IMHO more readable.

like image 173
hek2mgl Avatar answered Nov 06 '22 11:11

hek2mgl


Another method is the use of a here string (which has the benefit of eliminating the one-line pipe, but not the subshell):

./script.sh install <<<$(printf "y\n2\n1\nn\nn\n")

You may also be able to rely on the printf trick of printing all elements through a single format specifier and use process substitution (or use with the here string syntax above):

./script.sh install < <(printf "%c\n" y 2 1 n n)
like image 28
David C. Rankin Avatar answered Nov 06 '22 12:11

David C. Rankin