2

What would be a more straight forward readable way of these commands?

And why exit 255 and not exit 1?

[ $# -eq 3 ] || { echo error ; exit 255 ; }

grep -q "string" && exit 0
Anthon
  • 79,293

5 Answers5

5

Others have already mentioned that $# is the number of command-line arguments, so I'll ignore that part of your question.

Given cmd1 && cmd2, the shell first executes cmd1. If cmd1 fails, the entire expression fails. If cmd1 succeeds, the shell proceeds to execute cmd2. The entire expression succeeds if both cmd1 and cmd2 succeed. So, the && operator is the short-circuiting boolean AND applied to shell commands. Uses of this operator can be replaced with

if cmd1
then
    cmd2
fi

Given cmd1 || cmd2, the shell first executes cmd1. If it succeeds, the entire expression succeeds. Otherwise, the shell executes cmd2 and the success or failure of the expression is determined by cmd2. In short, this is the short-circuiting boolean OR applied to shell commands. You can replace this form with

if ! cmd1
then
    cmd2
fi

I've carefully used the phrases succeeded / succeeds and failed / fails above. Success, for shell commands, is defined as a process exit status of zero. Failure is any non-zero status. However, attempting to understand the && and || operators in terms of exit statuses is, at least to me, confusing since you end up with a weird sort of inverted logic.

3

This is pretty much straight forward, actually.

The script checks if it gets exactly 3 partameters, thats the [ $# -eq 3 ] part. If not, then the { echo error ; exit 255 ; } part will be executed. The exit code 255 has a special meaning, it means "Exit status out of range" see here. I think it's a bit missapplied here, but possible.

2

$# is the number of arguments to the shell. So, the first line says "exit if there are not 3 arguments", because the right part (after the ||) is only executed, if the left part is not true. || is the logical or.

255 as a return code may be arbitrary.

the scripts will return 0, if the word "string" is in the input.

Does this help?

  • Exit codes are not entirely arbitrary, especially 255 is not arbitrary! –  Feb 15 '12 at 15:46
1

On one side of the or operator you have the test ( [ ) function, if this evaluates to true (which it will when $# is equal to three) then we don't even need to bother checking the otherside. If it's false, we have to try the other side, which in this case is a function to echo an error and then exit. The same functionality could be accomplished with a more verbose script:

if [ $# -ne 3 ]
then
  echo error
  exit 255
fi
1

The line with the grep command does exit 0 if "string" is in the input, otherwise the exit code will be 1. A more explicit way would be:

grep -q "string"
if [ $? -eq 0 ]
then
  exit 0
else
  exit 1
fi