mercredi 13 février 2019

Why does a string equal zero in bash test

I have an array which I am using to generate a list which a user can choose from made like this.

list=(a b c d)
n=0
for x in ${list[@]}
    do echo $n\)$x
    n=$((n++)
read -p "Pick an item:" choice

I want to allow only valid options to be chosen so I am checking like this.

if [[ $choice -gt ${#list[@]} && $choice -lt -1 ]]
    then ...
else
    echo "not a valid choice"

The issue I am having is all strings evaluate at equal to zero. ie [[ "I am a duck" -eq 0 ]] is True, as is (( "I am a duck" == 0 )). Is there a way to make all string and number comparison evaluate to false? I know I can check for a string with [[ $choice =~ [A-Za-z]+ ]], but I am wondering if there is a way without regular expressions?

Aucun commentaire:

Enregistrer un commentaire