'How to represent multiple conditions in a shell if statement?
I want to represent multiple conditions like this:
if [ ( $g -eq 1 -a "$c" = "123" ) -o ( $g -eq 2 -a "$c" = "456" ) ]
then
echo abc;
else
echo efg;
fi
but when I execute the script, it shows
syntax error at line 15: `[' unexpected,
where line 15 is the one showing if ....
What is wrong with this condition? I guess something is wrong with the ().
Solution 1:[1]
In Bash:
if [[ ( $g == 1 && $c == 123 ) || ( $g == 2 && $c == 456 ) ]]
Solution 2:[2]
Using /bin/bash the following will work:
if [ "$option" = "Y" ] || [ "$option" = "y" ]; then
echo "Entered $option"
fi
Solution 3:[3]
Be careful if you have spaces in your string variables and you check for existence. Be sure to quote them properly.
if [ ! "${somepath}" ] || [ ! "${otherstring}" ] || [ ! "${barstring}" ] ; then
Solution 4:[4]
g=3
c=133
([ "$g$c" = "1123" ] || [ "$g$c" = "2456" ]) && echo "abc" || echo "efg"
Output:
efg
g=1
c=123
([ "$g$c" = "1123" ] || [ "$g$c" = "2456" ]) && echo "abc" || echo "efg"
Output:
abc
Solution 5:[5]
In Bash, you can use the following technique for string comparison
if [ $var OP "val" ]; then
echo "statements"
fi
Example:
var="something"
if [ $var != "otherthing" ] && [ $var != "everything" ] && [ $var != "allthings" ]; then
echo "this will be printed"
else
echo "this will not be printed"
fi
Solution 6:[6]
#!/bin/bash
current_usage=$( df -h | grep 'gfsvg-gfslv' | awk {'print $5'} )
echo $current_usage
critical_usage=6%
warning_usage=3%
if [[ ${current_usage%?} -lt ${warning_usage%?} ]]; then
echo OK current usage is $current_usage
elif [[ ${current_usage%?} -ge ${warning_usage%?} ]] && [[ ${current_usage%?} -lt ${critical_usage%?} ]]; then
echo Warning $current_usage
else
echo Critical $current_usage
fi
Solution 7:[7]
You can also chain more than two conditions:
if [ \( "$1" = '--usage' \) -o \( "$1" = '' \) -o \( "$1" = '--help' \) ]
then
printf "\033[2J";printf "\033[0;0H"
cat << EOF_PRINT_USAGE
$0 - Purpose: upsert qto http json data to postgres db
USAGE EXAMPLE:
$0 -a foo -a bar
EOF_PRINT_USAGE
exit 1
fi
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dennis Williamson |
| Solution 2 | David Ferenczy Rogožan |
| Solution 3 | |
| Solution 4 | Peter Mortensen |
| Solution 5 | Peter Mortensen |
| Solution 6 | Community |
| Solution 7 | Peter Mortensen |
