I'm trying to understand a sed
command shown on ETA Lab's Rich’s sh (POSIX shell) tricks page, specifically in the trick Shell-quoting arbitrary strings:
quote () { printf %s\\n "$1" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/'/" ; }
In the third sed
command (\$s/\$/'/
), I understand the first $
is escaped to prevent the shell to interpret it as a hypothetical $s
variable, so it can be passed to sed
and be rightfully interpreted as the last line address for the s
command, but why escape the second $
? Shouldn't it correctly match the end of the line as-is ?
!#%&/?_-
etc. require you to escape the preceding dollar, and if e.g.$/
was only an existing special variable in Perl, or in the shell too... What if some future shell decided to add that as a non-standard special parameter?'\''
or\047
or\27
or similar for the single quotes inside the script. Similarly for the printf formatting string - instead of having it unqupoted and requiring doubling uyp on escapes,printf %s\\n "$1"
just quote it -printf '%s\n' "$1"
printf '%q\n' "$1"
orprintf '%s\n' "${1@Q}"
if your shell supports those constructs.printf '%q\n'
or${1@Q}
are not POSIX.If your shell supports those constructs
.