Bash script - Auto fill answer

余生长醉 提交于 2020-05-13 05:14:07

问题


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 ?


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/30563819/bash-script-auto-fill-answer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!