2

I am trying to run simple code block. It gives error on fourth line as "syntax error near `$1'"

=~ means Matches Regular Expression

How should I use '$1' variable with this operator?

Here is my code:

if [[ $1 -gt 3 ]] && [[ $1 -lt 7 ]]
then
echo "$1 is between 3 and 7"
elif [[ $1 =~ "Jeff"]] || [[ $1 =~ "Roger" ]] || [[ $1 =~ "Brian" ]]
then
echo "$1 works in the Data Science Lab"
else
echo "You entered: $1, not what I was looking for.."
fi
Bce
  • 158
  • 1
  • 2
  • 9
  • The first test (whether it's between 3 and 7) only makes sense if `$1` is a number; this test will mostly technically work, but since `$1` is sometimes expected to have non-numeric values, you should test whether that test even makes sense, before testing it. – Gordon Davisson Nov 26 '18 at 17:42

1 Answers1

3

Very funny indeed. You've typed the first condition in that line as [[ $1 =~ "Jeff"]], so without a space between "Jeff" and ]] bash interprets them as a single string, which is obviously not your pattern, and the whole parse fails and line structure crashes. If you add that space:

if [[ $1 =~ "Jeff" ]] || [[ $1 =~ "Roger" ]] || [[ $1 =~ "Brian" ]]

then it works... seemingly...

bipll
  • 11,131
  • 1
  • 15
  • 31
  • If you are using a regex anyway, the various strings could be combined into a single regex like `if [[ $1 =~ ^(Jeff|Roger|Brian)$ ]]` – tripleee Nov 26 '18 at 13:24
  • @tripleee Sure (and even if not regex, conditions still can be combined into a single disjunction). – bipll Nov 26 '18 at 15:24