I am trying to execute a bash script in this way:
bash -s < my_script
The reason, for context, is to run the script remotely through SSH. I realized that the script I want to run includes some commands that can prompt the user for input, under certain rare conditions. So I decided to try and understand how that would work out with bash -s.
I wrote a simple script like this:
cat
echo "finished"
and got the output:
echo "finished"
My understanding is that, since the script itself is the stdin, the cat
command simply starts reading the rest of the script.
But, if I just add an "if" to the script, the result changes. So if I run this:
if [ true ]
then
cat
echo "finished"
fi
I get this output:
finished
I don't understand what causes this difference.
bash
reads (at least) an entire statement at a time, no matter how many lines of the file that entails. which in your latter example is the entire if
statement. So by the time cat
is executed, there is nothing left for it to read on standard input.
You would see the same result, for example, with
{
cat
echo "finished"
}
as everything inside and including the {...}
is a single (compound) statement.
In the first example, the first statement is cat
by itself, leaving the echo
statement in standard input for cat
to read.