How to do a logical OR operation in Shell Scripting?
1 Expert Answer
Rize S. answered 03/23/23
Senior IT Certified Trainer, IT Developer & DBA Administrator
To perform a logical OR operation in shell scripting, you can use the double vertical bar (||) operator. Here's how you can modify your code to use this operator:
if [ "$#" -eq 0 ] || [ "$#" -gt 1 ]; then
echo "hello"
fi
In this code, the -eq and -gt operators are used to compare the number of arguments ($#) to the values 0 and 1, respectively. The || operator is used to combine the two conditions into a logical OR operation.
Note that the -o operator can also be used for a logical OR operation, but it is considered deprecated and may not work in all versions of the shell. Therefore, it is recommended to use || instead.
Also, make sure to use the correct comparison operators -gt and -eq for comparing integers, and not the greater-than (>) operator used for string comparison.
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Anthony B.
Square brackets and || for sure, as in the latter syntax you mentioned. In Bash you would need to get rid of the "" around $#. What shell are you using (echo $SHELL)?05/26/19