Find the answer to your Linux question:
Results 1 to 7 of 7
Any one know a way to do this? var1=true var2=false var3=true for a in \$var{1..3};do if [[ "$a" == "false" ]]; then echo "Yay" fi done where $a = would ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Aug 2011
    Posts
    1

    Using a incrementing variable in a for loop


    Any one know a way to do this?

    var1=true
    var2=false
    var3=true

    for a in \$var{1..3};do
    if [[ "$a" == "false" ]]; then
    echo "Yay"
    fi
    done


    where $a = would equal/equate to tha values of vars 1 - 3

  2. #2
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    Is this what you mean?
    Code:
    var1=true
    var2=false
    var3=true
    
    for a in $var1 $var2 $var3; do
      if [[ "$a" == "false" ]]; then
        echo "Yay"
      fi
    done

  3. #3
    Just Joined!
    Join Date
    Aug 2011
    Posts
    11
    I think this is not exactly what he wants to do.

    He has for example three variables which have the same basename but with a different number at the end (var1, var2, var3). Now he wants to access each variable by using something like this: $var$counter. And I think this can't be done.

  4. $spacer_open
    $spacer_close
  5. #4
    Just Joined!
    Join Date
    Mar 2007
    Location
    Bogotá, Colombia
    Posts
    46
    If that's the case, then perhaps he should consider arrays

    Code:
    var[1]=true
    var[2]=false
    var[3]=true
    Then he can access the values like this:

    Code:
    ${var[$COUNTER]}

  6. #5
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    ah, if that's the case, how about:
    Code:
    #!/bin/bash
    var1=true
    var2=false
    var3=true
    
    for i in `seq 1 3`; do
      eval a=$(echo \$var$i)
      echo var $i is $a
      if [[ "$a" == "false" ]]; then
        echo "Yay"
      fi
    done

  7. #6
    Just Joined!
    Join Date
    Aug 2011
    Posts
    11
    atreyu: Seems to work for me. But I am with LSalab, arrays are the better solution for this I think...

  8. #7
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    yeah, definitely arrays are better, if the variable subnames are numbers. this solution is really more useful if the subnames are letters (or for some crazy reason you can't use arrays).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •