Results 1 to 5 of 5

Thread: Bash - I'm sure this is possible, but how?

  1. #1
    Join Date
    May 2009
    Location
    Fareham, UK
    Beans
    Hidden!
    Distro
    Xubuntu 13.04 Raring Ringtail

    Bash - I'm sure this is possible, but how?

    In this example:
    Code:
    t=60
    for i in t; do
        if [ \$$i -eq 60 ]; then
            echo "the number is $i"
        else
            echo fail
        fi
    done
    This results is an error "Integer expression expected" The if statement is comparing the literal string of "$t" to 60 and obviously equates to false, how can i get bash to compare the result of the variable and compare 60 to 60 and equate to true,

    Thanks for any help
    Mark
    Catch me on Freenode - imark

  2. #2
    Join Date
    Feb 2009
    Location
    Dallas, TX
    Beans
    6,593
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: Bash - I'm sure this is possible, but how?

    Hi CaptainMark.

    Just remove the '\$':
    Code:
    ...
    if [ $i -eq 60 ]; then
    ...
    Let us know how it goes.
    Regards.

  3. #3
    Join Date
    Apr 2012
    Beans
    5,060

    Re: Bash - I'm sure this is possible, but how?

    I think maybe another problem is

    Code:
    t=60
    for i in t; do
    which means the [ $i -eq 60 ] is trying to test the string value "t" instead of the integer value of variable t ("$t") i.e.

    Code:
    $ t=60; for i in t; do echo $i; if [ $i -eq 60 ]; then echo "True"; else echo "False"; fi; done
    t
    bash: [: t: integer expression expected
    False
    $
    $ t=60; for i in "$t"; do echo $i; if [ $i -eq 60 ]; then echo "True"; else echo "False"; fi; done
    60
    True
    What is the purpose of the for .. in construct here?
    Last edited by steeldriver; May 8th, 2013 at 09:32 PM.

  4. #4
    Join Date
    Jun 2006
    Location
    Brisbane Australia
    Beans
    713

    Re: Bash - I'm sure this is possible, but how?

    It's not clear what you are wanting OP, but I suspect you are trying to work out how to use indirect variables in bash? E.g:
    Code:
    $ t=60
    $ i=t
    $ echo ${!i}
    60
    Here, ! is the bash indirection expansion operator.

  5. #5
    Join Date
    May 2009
    Location
    Fareham, UK
    Beans
    Hidden!
    Distro
    Xubuntu 13.04 Raring Ringtail

    Re: Bash - I'm sure this is possible, but how?

    I figured it out eventually, I simply wasn't using the correct terminology, once I discovered the term 'recursive variable substitution' I was away, I made use of the eval command as seen in my other post here http://ubuntuforums.org/showthread.php?t=2143690
    Catch me on Freenode - imark

Bookmarks

Posting Permissions

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