-1

I am trying to understand following pice of code:

for f in *.out; do sort -cg <$f &>/dev/null && res="sorted" || res="unsorted"; echo "File $f is $res."; done

For loop iterates through all .out files and gives each one as a parameter to sort, and the output of the sort is redirected into "nothing". But can someone explain what: && res="sorted" || res="unsorted" does?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
GraphLearner
  • 179
  • 1
  • 2
  • 11

1 Answers1

6

A command after the && will only be executed if the previous command exited with a 0 (zero) status code. The other || works in the opposite way - a command after a || will only execute if the previous command exited with a non-zero exit code.

Here is a small example:

cat /some/file/that/is/missing && echo 'Found the file!' # doesn't print 
cat /some/file/that/is/missing || echo 'Unable to find the file!' # will print 

With the first line, the echo command will not execute since the cat command failed (because the file doesn't exist)

With the second line, we WILL see the echo command because the cat command failed.

Lix
  • 47,311
  • 12
  • 103
  • 131