4

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}')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt
  • 153
  • 2
  • 8

3 Answers3

6

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}')
"
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • The double quoted string looks like the best solution for me. Thanks very much! – Matt Mar 07 '14 at 14:23
  • The simplest way I know of is to use ```printf``` to convert any string to a bash-escaped string: ```printf "%q" "$str"``` – exbuddha Oct 31 '17 at 21:59
2

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.)

chepner
  • 497,756
  • 71
  • 530
  • 681
  • For [Bash 2.04 and later](https://stackoverflow.com/questions/1250079/how-to-escape-single-quotes-within-single-quoted-strings/16605140#16605140)? – Peter Mortensen Aug 16 '23 at 19:18
0

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

e.g.:

$ echo "first second third" > ex.txt
$ awk '{print $3}' ex.txt
third
$ cut -d" " -f3 ex.txt
third
jimm-cl
  • 5,124
  • 2
  • 25
  • 27