0

Below is my program, a.sh :

A=10 B=20 C=0 D=1

for var in {A,B,C,D}
do
    if [ $var = 0 ]
    then
        echo "$var value is 0"
    else
        echo "Ok" 
    fi
done

Result is :

# sh a.sh

Ok
Ok
0 value is 0   <==== Instead of this I want  "C value is 0"
Ok

How can we do this ?

2
  • 1
    I would not recommend you develop shell scripts as root. Commented Mar 19, 2017 at 8:42
  • I don't see any way that script could be generating that output. Commented Mar 19, 2017 at 9:11

1 Answer 1

6

With bash:

A=10
B=20
C=0
D=1

for var in A B C D; do
    if [ ${!var} -eq 0 ]; then
        echo "$var value is 0"
    else
        echo "Ok"
    fi
done

Use -eq to compare integer values (or use (( ${!var} == 0 )) or (( !${!var} )) which is the same thing), and use ${!var} to get the value of the variable whose name is stored in the variable var.

Or, a bit neater but essentially the same (still in bash):

for var in A B C D E; do
    case ${!var} in
        0) printf '%s value is 0\n' "$var" ;;
        *) echo 'Ok' ;;
    esac
done

This treats the values as strings, not as integers.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.