简体   繁体   中英

Bash: Use single quotes inside a variable

I have the following script (to get my current IP from an external service):

#!/bin/bash
####################################################################
# Gets the public IP address of current server
####################################################################

cmd='curl -s'
#cmd='wget -q -O'
#cmd='lynx -dump'

ipservice=checkip.dyndns.org

pipecmd="sed -e 's/.*Current IP Address: //' -e 's/<.*\$//'"

# Run command
echo $($cmd $ipservice | $pipecmd)

But sed command complains:

sed: -e expression #1, char 1: unknown command: `''

I have been googling around on how to use single quotes inside a variable without success.

Thanks!

The command is split into words sed , -e , 's/.*Current , IP , Address: , //' etc., so the first command in the sed program indeed starts with ' , which is not a valid sed command. Use an array and quoting instead:

cmd=(curl -s)
pipecmd=(sed -e 's/.*Current IP Address: //' -e 's/<.*$//')
"${cmd[@]}" "$ipservice" | "${pipecmd[@]}"

Note that echo "$(command)" is equivalent to command . In general, make sure that you always quote all variables (there are a few exceptions, though).

You need to use eval to get the shell to interpret the contents of the variable

echo $($cmd $ipservice | eval $pipecmd)

You may need extra escaping because of the extra evaluation, although in this particular case I think it's okay as is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM