0

i want to check multiple variables in bash but end up too much, is there any way to shorten this

i end up like this

if [[ $1 == -a || $2 == -a || $3 = -a ]] && [[ $1 == -b || $2 == -b || $3 = -b ]] && [[ $1 == -c || $2 == -c || $3 = -c ]] && [ $# -eq 4 ]; then
echo "insert some words"
exit
fi

i've tried this to shorten it but won't work

a=-a
b=-b
c=-c
if [[ ${@:1:3} == $a || ${@:1:3} == $b || ${@:1:3} == $c ]] && [ $# -eq 4 ]; then
echo "insert some words"
exit
fi

is there any way to shorten this? thanks in advance!

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Moonbeam
  • 11
  • 3

1 Answers1

1

Options with getopts

while getopts ":a:b:c:" opt; do
    case $opt in
        (a) a=$OPTARG;;
        (b) b=$OPTARG;;
        (c) c=$OPTARG;;
    esac
done

echo $a $b $c

Or with just case

while [[ $@ ]]; do
    case $1 in
        (-a) a=$2;;
        (-b) b=$2;;
        (-c) c=$2;;
    esac; shift
done

echo $a $b $c
Ivan
  • 6,188
  • 1
  • 16
  • 23
  • 1
    You would need a colon after `c` in the optstring – glenn jackman Sep 11 '20 at 13:57
  • 1
    We have other examples already in the knowledge base that cover this ground, and do it more thoroughly. In [How to Answer](https://stackoverflow.com/help/how-to-answer), see the section *Answer Well-Asked Questions*, and therein the bullet point regarding questions that "have been asked and answered many times before". – Charles Duffy Sep 11 '20 at 14:10
  • @ivan thank you so much for this.. i will try hopefully this solved my problem – Moonbeam Sep 11 '20 at 14:24