0

I want to append the value as $EC5 in my newlist in shell script. However, it is currently storing value as 11 in newlist array.

EC2=0
EC3=0
EC4=0
EC5=11
return_codes=( $EC2 $EC3 $EC4 $EC5)
newlist=()

for i in "${return_codes[@]}";
do
    if [[ $i -ne 0 ]]
        then
            newlist+=($i)
    fi
done

Kindly Help.

2
  • 1
    $EC5 is 11. Or do you mean you want to store the string EC5 itself? Leave out the $ then. When you run return_codes=( $EC2 $EC3 $EC4 $EC5 ), that does return_codes=( 0 0 0 11 ); the place where each of those numbers originally came from is lost. Commented Mar 18, 2020 at 21:45
  • There are no arrays in POSIX [shell] so you should add the proper tag for the shell you are using. [bash]? Commented Mar 18, 2020 at 22:26

1 Answer 1

2

Instead of storing the variable's value, you can store its name and look that up:

EC2=0
EC3=0
EC4=0
EC5=11
return_codes=( EC2 EC3 EC4 EC5)
newlist=()

for i in "${return_codes[@]}";
do
    if [[ ${!i} -ne 0 ]]
        then
            newlist+=($i)
    fi
done
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.