LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   BASH Script. Result of command input into variable (https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-result-of-command-input-into-variable-917308/)

bcyork 12-05-2011 08:40 PM

BASH Script. Result of command input into variable
 
Hi, I have been trying to figure this out and also new to bash scripting as well. How can I put the result of a command into a variable such as this.

CURRENT='wget -O - -q icanhazip.com'

So if I would run

echo $CURRENT

I would get an IP address?

Right now echo returns the command. I can't seem to figure out how exactly to do this. In the end I need two variables. One an IP address returned as my current external IP and the second a variable read from a file that would be an IP address as well.

Thanks!

corp769 12-05-2011 08:43 PM

Here is what you need:
Code:

#!/bin/bash
var1=$(wget -O - -q icanhazip.com)
echo $var1

You need to tell it to execute the command, instead of trying to display it. You can alternatively use backticks, as such:
Code:

`wget -O - -q icanhazip.com`
Cheers,

Josh

bcyork 12-05-2011 08:58 PM

Thanks Josh, did the trick!

-Brian

corp769 12-05-2011 10:45 PM

No problem! Please mark your thread as solved using the thread tools located at the top of the page, thanks!

Cheers,

Josh

David the H. 12-06-2011 12:57 PM

Note that $(..) is highly recommended over `..`.

A while back I wrote up a script/function that polls a random site for your external ip address, and keeps trying until it gets a successful hit. You can easily edit the list if you discover new ones or one goes bad. I currently have seven working addresses.

Code:

#!/bin/bash

get_current_ip() {
        local -a ipsite
        local -i xc num i

        ipsite=(
                "http://automation.whatismyip.com/n09230945.asp"
                "http://www.showmyip.com/simple/"
                "http://cfaj.freeshell.org/ipaddr.cgi"
                "https://secure.informaction.com/ipecho/"
                "http://icanhazip.com/"
                "http://wooledge.org/myip.cgi"
                "http://ifconfig.me/ip"
              )

        xc=1
        num=${#ipsite[@]}

        until (( xc == 0 )) ; do
                (( i = RANDOM % num ))
                ip=$( wget -t 1 -T 5 -q -O- "${ipsite[i]}" )
                xc=$?
        done

        #some of the sites may output a newline or other junk, so remove any cruft.
        printf "%s" "${ip//[^0-9.]}"
}

get_current_ip

exit 0



All times are GMT -5. The time now is 09:49 PM.