cab00t
cab00t

Reputation: 85

Bash shell argument passing...?

You can use a semicolon in bash shell to specify multiple commands. Sometimes, one of those commands pops a question, requiring user input. (typically 'y' / 'n', or whatever really) If I know what I want to answer in advance, is there a way to parse it to the commands somehow, like an argument, or some weird magical pipe stuff?

Upvotes: 1

Views: 111

Answers (5)

Yann Vernier
Yann Vernier

Reputation: 15877

First, it's not bash popping these questions. It is the particular program called (for instance, cp -i asks before overwriting files). Frequently those commands also have switches to answer the questions, like -y for fsck, or how -f overrides -i in rm. Many programs could be answered through a pipe, which is why we have the command "yes", but some go to extra lengths to ensure they cannot; for instance ssh when asking for passwords. Also, there's nothing magical about pipes. If the program only sometimes asks a question, and it matters what question, there are tools designed for that such as "expect".

In a typical shell script, when you do know exactly what you want to feed in and the program accepts input on stdin, you could handle it using a plain pipe:

echo -e '2+2\n5*3' | bc

If it's a longer piece then a here document might be helpful:

bc <<EOF
2+2
3*5
EOF

Upvotes: 2

ezaquarii
ezaquarii

Reputation: 1916

Sometimes a command provides an option to set default answer to a question. One notable example is apt-get - a package manager for Debian/Ubuntu/Mint. It provides and options -y, --yes, --assume-yes to be used in non-interactive scripts.

Upvotes: 1

bobah
bobah

Reputation: 18864

For the simple "yes" answer there is a command yes, available on most Unix and Linux platforms:

$ yes | /bin/rm -i *

For an advanced protocol you may want to check the famous Expect, also widely available. It needs basic knowledge of Tcl.

Upvotes: 2

Bart
Bart

Reputation: 31

You can use the yes command to put a lot of 'y' 's to a pipe.

For example, if you want to remove all your text files, you can use

yes | rm -r *.txt

causing every question asked by rm being answered with a y. If you want another default answer, you can give it as an argument to yes:

yes n | rm -r *.txt

This will output a 'n'.

For more information, see http://en.wikipedia.org/wiki/Yes_(Unix)

Upvotes: 2

Mat
Mat

Reputation: 206699

You don't need any "weird magical pipe stuff", just a pipe.

./foo ; echo "y" | ./bar ; ./baz

Or magical herestring syntax if you prefer:

./foo ; ./bar <<<"y" ; ./baz

Upvotes: 2

Related Questions