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.