asimes asimes - 2 months ago 9
Bash Question

Combine shell boolean conditions with selective precedence

I have two conditions at the beginning of a script to verify arguments. The intention is that exactly two arguments should be passed and the first argument must be

"FOO"
or
"BAR"
. What I have below works, but I want to know how to make this a single if statement:

#!/bin/bash

if [ "$#" -ne 2 ]; then
echo "Usage: $0 <FOO or BAR> <Removed for SO>"
exit
fi
if [ "$1" != "FOO " -a "$1" != "BAR" ]; then
echo "Usage: $0 <FOO or BAR> <Removed for SO>"
exit
fi


Just to clarify, what I am asking is how in general to combine "logical and" with "logical or" in a shell script. In pseudo code this is what I would want:

if ( numArgs != 2 || (someArg != "FOO" && someArg != "BAR") )

Answer

You can use || between 2 conditions:

if [ "$#" -ne 2 ] || [ "$1" != "FOO" -a "$1" != "BAR" ]; then
        echo "Usage: $0 <FOO or BAR> <Removed for SO>"
        exit
fi