0
vars="a,b"
a="True"
b="False"
IFS=","
for var in $vars; do
  if [[ "$var" = "True" ]]; then
    echo "True found"    
  fi
done

I would expect the above bash script to print out "True found". But it does not print anything. Any ideas as to why ?

8
  • vars="a,b" is not an array Commented Jun 15, 2015 at 23:30
  • 1
    You want indirect variables. See mywiki.wooledge.org/BashFAQ/006 Commented Jun 15, 2015 at 23:32
  • 1
    You are expecting bash to double-evaluate the variable contents. It isn't going to do that. You need to do the second level of indirection yourself. Commented Jun 15, 2015 at 23:33
  • 1
    ...as it is, err, why would you expect $var to evaluate to True or False, rather than a or b? Commented Jun 15, 2015 at 23:33
  • 1
    Add set -x to the top of this script to see what is actually happening at each step to better understand what is going on. Commented Jun 15, 2015 at 23:34

1 Answer 1

2

Make this:

if [[ "${!var}" = "True" ]]; then

${!varname} expands the variable named in $varname. Otherwise, you get the name itself, not the contents of the variable with that name.

See BashFAQ #6 for far more details.

Sign up to request clarification or add additional context in comments.

1 Comment

Indirect variables. Nice. TIL.

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.