Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

whats the best practice for conditionals in bash when checking multiple statements?

Tags:

bash

Given your trying to check that a variable is not empty and not some other value as in the following code:

if [ ! -z "$foo" ] && [[ ${foo} != "bar" ]]; then

what is the best practice for accomplishing this. I've seen bash conditionals written several ways including the following...

if [[ ! -z "$foo" && ${foo} != "bar" ]]; then

I understand there is a difference when using the single brackets and the double, I'm more concerned with when to put the && or || inside the brackets or out.

like image 512
iamnewton Avatar asked Jan 10 '23 17:01

iamnewton


2 Answers

Put &&/|| inside brackets for [[ ]]. Outside is also accepted.

Put &&/|| outside brackets for [ ]. Inside is NOT allowed.

This is due to the fact that && binds normal commands together based on return value, e.g.

wget file && echo "Success"

[, despite its funny name, is a regular command and obeys the same rules as e.g. wget or echo.

[ foo || bar ] is two commands, [ foo and bar ], neither of which are valid.

[[ .. ]] on the other hand is not a normal command but special shell syntax. [[ foo || bar ]] is a single command, and interpretted accordingly.

like image 163
that other guy Avatar answered Jan 13 '23 07:01

that other guy


To complete the previous answers :

if [[ ! -z $foo && $foo != "bar" ]]; then ...
# [[ will execute the two conditions with "and" operator in a single instruction

Is equivalent of :

if [[ ! -z $foo -a $foo != "bar" ]]; then ...
# [[ will execute the two conditions with "and" operator in a single instruction

But not equivalent of :

if [[ ! -z $foo ]] && [[ $foo != "bar" ]]; then ...
# second [[ will be executed if the first success ($? = 0)

-a (and) and -o (or) will work with test and [.

See man test to get more details ;)

Otherwise, no need to protect your variables by doubles quotes with [[ and no need to use delimiters (${}) in this case.

Here is a reminder about the necessity (or not) to protect your variables with double quotes..

like image 22
Idriss Neumann Avatar answered Jan 13 '23 05:01

Idriss Neumann