Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precedence of operators in Bash

Tags:

operators

bash

I have an expression cat file.txt | script.sh 1> output.txt || mkdir TEST &. Does & at the end mean that only mkdir executes in the background or the whole expression?

like image 847
Mark Crawford Avatar asked Jun 13 '18 11:06

Mark Crawford


2 Answers

Regarding the &, it will affect the whole expression. You can easily check it with something not as elegant as simple like:

echo '1' > file1  || echo '2' > file2 &

(to put some output redirection as you have), otherwise, just

echo '1' || echo '2' &

Here the output of the first echo will return true and the second part in the condition won't be executed, but it will go to the background anyways.

and then, you can check:

false || echo '2' > file2  &

or the easier version:

false || echo '2' &

Here, the echo will be executed, and also in background.

Then, in both cases it will be executed in background, even if in the first case only the first part is executed and in the second only se second part is executed.

like image 123
myradio Avatar answered Sep 27 '22 23:09

myradio


& and ; are separators in the POSIX shell language. They apply to whole pipelines.

You can either devise an experiment to (dis)prove it:

[ ! -d TEST ] || rmdir TEST #cleanup
sleep 1 | (sleep 1 ; false) || mkdir TEST & 
ls -d TEST #will run immediately (because & applied to the whole pipeline) 
#but fail because the `||` part wasn't reached yet

Or you can look it up in the POSIX specification for the shell grammar.

like image 23
PSkocik Avatar answered Sep 27 '22 22:09

PSkocik