I try to set variable which get interface ip-address from ifconfig
and read it later. But when I execute a echo
command, variable still empty. Please look at my code:
/usr/bin/bash -c "HOST_IPS=$(/usr/bin/ifconfig | /usr/bin/awk 'BEGIN {cnt=0} {if($0 ~ /inet / && cnt==1) {print $2} cnt++}'); echo $HOST_IPS"
But /bin/echo work fine with same command:
/usr/bin/bash -c "echo $(/usr/bin/ifconfig | /usr/bin/awk 'BEGIN {cnt=0} {if($0 ~ /inet / && cnt==1) {print $2} cnt++}')"
A variable in bash is created by assigning a value to its reference. Although the built-in declare statement does not need to be used to explicitly declare a variable in bash, the command is often employed for more advanced variable management tasks.
The format is to type the name, the equals sign = , and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.
Sets VAR with the value of first argument, and if the argument is not set, DEFAULTVALUE is used. Notice the colon and dash characters. This little function starts a simple HTTP server that serves from current directory.
To set (or change) a environment variable, use command " set varname=value ". There shall be no spaces before and after the '=' sign. To unset an environment variable, use " set varname= ", i.e., set it to an empty string.
You have to escape the $
sign in the final echo command, or the variable $HOST_IPS
will be substituted into the command string before the subshell is spawned:
/usr/bin/bash -c "HOST_IPS=$(/usr/bin/ifconfig | /usr/bin/awk 'BEGIN {cnt=0} {if($0 ~ /inet / && cnt==1) {print $2} cnt++}'); echo \$HOST_IPS"
For more immediate visibility:
# v-- insert backslash here
/usr/bin/bash -c "HOST_IPS=$(same as before); echo \$HOST_IPS"
Contrary to @gniourf_gniourf's comment, it is not actually necessary to escape the other dollar signs. However, as written, the command substitution is not performed by the subshell (!); its result is substituted into the command string that is passed to the subshell. The calls
mypid() { echo $$; }
bash -c "pid=$(mypid); echo \$pid; mypid"
demonstrate the way it works: it will once print the PID of the parent shell and once complain that mypid
is not a known command because the subshell does not know the function.
Since running the ifconfig | awk
command in the parent shell is unlikely to be a problem, you can probably leave the command substitution part unchanged. If it is important that the command be run by the subshell, you'll have to escape all the things there as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With