Results 1 to 3 of 3

Thread: store result in a variable?

  1. #1
    Join Date
    Jul 2012
    Beans
    3

    store result in a variable?

    Hi all i have basically one question.
    Is it possible to place the result from ifocnfig (or a part of result) in a variable?

    Couldn't find the answer in this form dos somone know the answer.
    Thanks

  2. #2
    Join Date
    Apr 2012
    Beans
    5,859

    Re: store result in a variable?

    in general, bash lets you return the output of a command using $(command), e.g.

    Code:
    $ result=$(ifconfig)
    $ echo $result
    it's probably not very useful unless you select out part of the output (using grep for example)

  3. #3
    Join Date
    Jul 2007
    Location
    Burlington, NC
    Beans
    1,994
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: store result in a variable?

    For the Bash shell, the ancient syntax for this is the backticks (the left quote usually above the tab key).

    But the more modern syntax is the $( ... ) construct:

    Code:
    #old and deprecated
    variable=`ifconfig eth0`
    
    #new-er and shiny
    variable=$( ifconfig eth0 )
    As mentioned above, it can be difficult to parse after the fact. Also, if you try to parse it afterwards, you'll quickly pick up on some of the wonders of quoting variable references...

    Code:
    $ echo $variable
    eth0 Link encap:Ethernet HWaddr 00:90:f5:aa:af:e5 UP BROADCAST MULTICAST
    MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0
    TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0
    txqueuelen:1000 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
    Interrupt:35 Base address:0xe000
    $ echo "$variable"
    eth0      Link encap:Ethernet  HWaddr 00:90:f5:aa:af:e5  
              UP BROADCAST MULTICAST  MTU:1500  Metric:1
              RX packets:0 errors:0 dropped:0 overruns:0 frame:0
              TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
              collisions:0 txqueuelen:1000 
              RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
              Interrupt:35 Base address:0xe000
    The first command, missing the quotes, creates the illusion that the $( ... ) command failed to capture properly, but in reality, the shell parser itself will eat whitespace on a variable when it is referenced; if the quotes are omitted. Long story short (too late ), it's almost always a good idea to quote all variable references.
    Last edited by asmoore82; July 30th, 2012 at 06:55 PM.

Tags for this Thread

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
  •