Reputation: 7318
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!
Upvotes: 3
Views: 670
Reputation: 49812
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).
Upvotes: 5
Reputation: 61369
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.
Upvotes: 3