Bash: use single quotes inside a variable

I have the following script (to get my current IP address 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 the sed command complains:

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

I was looking for ways to use single quotes inside a variable without success.

Thank!

+3
source share
2 answers

The team is divided into words sed, -e, 's/.*Current, IP, Address:, //'etc, so the first team in the program sedreally begins with 'that is not a valid command sed. Use an array instead and instead:

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

, echo "$(command)" command. , , ( ).

+5

eval,

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

- , , , .

+3

All Articles