Linux Bash – What Do These Commands Mean?

bashlinux

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

Best Answer

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.