spiderplant0
spiderplant0

Reputation: 3952

Bash expression combined with return code from a command

I want to test for a condition and if true run a command and if non-zero, execute the body of the if.

I've tried all manner of combinations of [] and -a and && and $() and cant figure it out. The attempt below gives error of: [: too many arguments

(This is just a simplified example, the question is also about understanding more about bash rather than solving a particular problem.)

numMd5Files=1

if [ ${numMd5Files} -eq 1 ] -a [ ! $( md5sum -c md5.txt ) ] ; then
    echo "md5 error"
fi

Upvotes: 1

Views: 112

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753960

You probably need:

if [ ${numMd5Files} -eq 1 ] && md5sum -c md5.txt; then

The number of files must be 1 and the md5sum command must be successful for the then block to be executed. You may end up redirecting the output of md5sum to /dev/null so you don't see what it says:

if [ ${numMd5Files} -eq 1 ] && md5sum -c md5.txt >/dev/null 2>&1; then

And if you're only interested in md5sum failures, then the exit status of md5sum can be inverted with the Bash built-in ! command:

if [ ${numMd5Files} -eq 1 ] && ! md5sum -c md5.txt; then

The if command simply tests the exit status of commands. When you use [, the [ command is executed and produces an zero or non-zero exit status. If the exit status is 0, it is successful, and the then clause is executed. If the exit status is not 0, it fails, and the elif or else clause (if present) is executed instead.

There is often an external command /bin/test aka /bin/[ — but most modern shells also have a built-in variant of test and [ that is executed in preference to the external command.

With the && operator, the command on the left is executed; if it is successful, the command on the right is executed, and if it is successful too, the then clause is executed.

The [[ operator is only available as a built-in to the shell.

I still have the code for an external command not (first version in 1991), which I used to use sometimes, and could be installed with a link named !, so that for shells without a built-in ! command, I could still invert the exit condition of a command. It is not very complex!

Upvotes: 2

Related Questions