Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single quote escaping in Bash within a single quoted string

Tags:

bash

shell

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}')
like image 749
Matt Avatar asked Sep 07 '25 10:09

Matt


1 Answers

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}')
"
like image 127
Sven Marnach Avatar answered Sep 10 '25 18:09

Sven Marnach