Print a string including single quotes and other special characters

You need to either keep using single quotes, but then print out the ones you need in the output "separately", or use double quotes and escape the dollar signs.

For the second option:

print "clock=\$(prtconf -s | awk '{print \$4,\$5}')" > test.txt

For the first:

print 'clock=$(prtconf -s | awk '\''{print $4,$5}'\'')' > test.txt

(That's 'text' then escaped single quote \' then 'other text'.)

For the sake of completeness, note that print expands backslash-character escape sequences (this doesn't matter in your case because the string you want to print doesn't contain any backslash). To avoid this, use print -r.


The simple way to do it is to use single quotes '…' around the string. Single quotes delimit a literal string, so you can put it anything between them except a single quote '. To insert a single quote in the string, use the four-character sequence '\'' (single quote, backslash, single quote, single quote).

Technically, there's no way to put a single quote inside a single-quoted literal. However consecutive literals are just as good as a single literal. 'foo'\''bar' is parsed as

  1. the single-quoted literal foo
  2. the backslash-quoted literal character '
  3. the single-quoted literal bar

This effectively means that '\'' is a way to escape a single quote in a single-quoted literal.

Note that the ksh print command performs backslash expansion. Add the -r option to avoid this. It won't hurt you because there happens to be no backslash in the string you want to print, but it's better to use -r, in case a backslash is added during maintenance.

print -r -- 'clock=$(prtconf -s | awk '\''{print $4,$5}'\'')' > test.txt

Alternatively, you can use the POSIX method to print a string literally with a newline at the end:

printf '%s\n' 'clock=$(prtconf -s | awk '\''{print $4,$5}'\'')' > test.txt