Issue
I'm building a bash script which have 2 conditions within an IF statement, linked by an AND logic operator, but it complains when executing. Just for the record, if I run each condition in it's unique IF, both works just fine. Problem arises when I try to execute both glued by the -a (AND) operator. Here it is:
if [[ "$1" =~ ".com" -a test "$#" -eq 1 ]]
then
echo "olalá"
fi
I'll appreciate any tip on this issue.
Solution
-a
is the AND operator in a [ ]
test expression, but [[ ]]
conditional expressions use &&
instead. Also, there is a stray test
in the expression that doesn't belong there at all. Here's the corrected version:
if [[ "$1" =~ ".com" && "$#" -eq 1 ]]
You could equivalently use two separate [[ ]]
expressions and use &&
between them:
if [[ "$1" =~ ".com" ]] && [[ "$#" -eq 1 ]]
(If you were using [ ]
expressions, this would be the preferred method because of ambiguities in the syntax involving -a
, -o
, and such; but with [[ ]]
, there's no ambiguity and either method works fine.)
Answered By - Gordon Davisson Answer Checked By - Terry (WPSolving Volunteer)