1

how to make several comparisons in the bash by placing the condition and comparison points next to instead of the long queue ?

that something like this

before :

if [[ $var == "aaa" || $var == "bbb" || $var == "ccc" || $var == "ddd" ]];
then
 echo "good";
fi

after (what I want):

if [[ $var==["aaa","bbb","ccc","ddd"] ]];
then
 echo "good";
fi
Gilles Quenot
  • 143,367
  • 32
  • 199
  • 195

2 Answers2

2

With extended pattern matching:

shopt -s extglob
[[ $var = @(aaa|bbb|ccc|ddd) ]] && echo "good"
PesaThe
  • 6,628
  • 1
  • 13
  • 37
1

Try this using bash regex with the keywork =~:

if [[ $var =~ ^(aaa|bbb|ccc|ddd)$ ]];
then
 echo "good";
fi

Edit :

As seen in comments, for real you need to compare int, not strings, so :

((var%3 == 0)) && echo "ok"

Using bash arithmetic

Gilles Quenot
  • 143,367
  • 32
  • 199
  • 195
  • 1
    I suggest to add `^` and `$`: `^(aaa|bbb|ccc|ddd)$` – Cyrus Feb 17 '18 at 16:39
  • You really need `^` and `$` outside the parentheses just like [Cyrus](https://stackoverflow.com/questions/48843438/how-to-simplify-the-comparison-in-the-bash/48843617#comment84691216_48843511) suggested. This will match strings like `qbbbq`. – PesaThe Feb 17 '18 at 16:50
  • Oops, doing too much things at the same time, thanks :) – Gilles Quenot Feb 17 '18 at 16:57
  • I will compare the hours of the day, I need every third hour, I will compare the current hour with 0,3,6,9,12,15,18,21 and send an email, I do not need to compare the lines yet, but thanks a lot, if necessary I will do according to your example – Дмитрий Смирнов Feb 17 '18 at 16:58
  • @ДмитрийСмирнов You might consider using something like `if ! ((var%3)); then echo "good"; fi`. – PesaThe Feb 17 '18 at 17:02
  • @ДмитрийСмирнов: or `[[ $((var%3)) == 0 ]]` – Cyrus Feb 17 '18 at 17:05