Scroll through an array bash script

Asked

Viewed 482 times

2

Can someone give me an example of an if and case running through an array in bash script? I’m just finding an example of what it’s for to list the items.. I’m trying to make sure 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

1 answer

3


You don’t need to juggle with arrays, the syntax of case/esac allows you to test a list of values separated by |, look at you:

#!/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 the use of arrays is a mandatory prerequisite, there is a solution using conditional if/elif/else/fi with the operator =~, verifying whether a specific value is contained within a 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 letters contained in the variable $RESP be read in small print (lowercase), making it indifferent if what was typed by the user was in low box (lowercase) or high-cash (uppercase).

  • Cara couldn’t have a more complete answer than his, especially the ${RESP,} tip that I didn’t know haha, thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.