简体   繁体   中英

single quote escaping in bash within single quoted string

The problem

I'm trying to create a kickstart file automatically, and the tool i'm using to parse it requires the kickstart to be supplied as a string in single quotes.

Most of it is fine, except the postinstall script which uses awk, hence single quotes within single quotes.

I've looked at some of the other posts, and tried escaping the strings, to no avail.

I've clearly mis-understood some fundamental principal of escaping.

The code

DATA='
GATEWAY=$(localcli network ip route ipv4 list | grep default | awk \'{print $3}\')
'
echo ${DATA}

The desired output

This is the literal output string i'd like to see.

GATEWAY=$(localcli network ip route ipv4 list | grep default | awk '{print $3}')

Any help would be much appreciated!

Thanks

Matt

Since you can't escape characters within the single-quoted string, you have to do it outside of it:

~$ echo 'abc'\''cde'
abc'cde

Alternatively, use a double-quoted string (requires escaping $ )

DATA="
GATEWAY=\$(localcli network ip route ipv4 list | grep default | awk '{print \$3}')
"

There is a little-known third type of quotes— $'...' —available to bash in which you can escape single quotes:

DATE=$'GATEWAY=$(...| awk \'/default/ {print $3}\')'

(This also demonstrates why piping grep into awk is often unnecessary.)

If you must use single quotes in your DATA variable definition, replacing awk with cut could be a workaround.

eg:

$ echo "first second third" > ex.txt
$ awk '{print $3}' ex.txt
third
$ cut -d" " -f3 ex.txt
third

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