Go through a bash script array

2

Can anyone give me an example of an if and case traversing an array in bash script? I'm just setting an example with for what's to list the items .. I'm trying this way but it's not right. ex:

v1=("sim" "s" "y" "yes" "")
v2=("não" "no" "nao")

read -p "Digite sua opção [S] [n]" RESP

case $RESP in
$V1)
echo "Opção sim"
;;
$V2)
echo "Opção não"
;;
*)
echo "Não conheço"
;;
esca
    
asked by anonymous 08.07.2018 / 03:41

1 answer

3

You do not need juggling with arrays , the syntax of case/esac allows you to test a list of values separated by | , see:

#!/bin/bash

read -p "Digite sua opção [S/N]: " RESP

case ${RESP,,} in

    "sim"|"s"|"y"|"yes"|"")
        echo "Opção sim"
    ;;

    "não"|"n"|"nao"|"no")
        echo "Opção não"
    ;;

    *)
        echo "Não conheço"
    ;;

esac

However, if using arrays is a mandatory prerequisite, there is a solution using the if/elif/else/fi conditionals with the =~ operator, which checks whether a specific value is contained within an array :

#!/bin/bash

v1=("sim" "s" "y" "yes" "")
v2=("não" "no" "nao" "n")

read -p "Digite sua opção [S/N]: " RESP

if [[ "${v1[@]}" =~ "${RESP,,}" ]]; then
    echo "Opção sim"
elif [[ "${v2[@]}" =~ "${RESP,,}" ]]; then
    echo "Opção não"
else
    echo "Não conheço"
fi

Notice that ${RESP,,} causes all the letters contained in the $RESP variable to be read in lowercase ), making it indifferent whether what the user typed was lowercase ( lowercase ) or uppercase ).

    
08.07.2018 / 04:56