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? – ilkkachu Mar 02 '23 at 21:38'\''or\047or\27or 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"– Ed Morton Mar 03 '23 at 16:40printf '%q\n' "$1"orprintf '%s\n' "${1@Q}"if your shell supports those constructs. – Ed Morton Mar 03 '23 at 16:59printf '%q\n'or${1@Q}are not POSIX. – MoonSweep Mar 04 '23 at 00:09If your shell supports those constructs. – Ed Morton Mar 04 '23 at 00:10$sis required to expand to the contents of thesvariable, but$/is unspecified and could expand to anything as far as POSIX is concerned. I don't know of any current shell where$/expands to anything other than$/but future ones may.$!,$@,$*,$-,$?are already special in all Bourne-like shells,$(in Korn/POSIX ones.$[in bash/zsh,$^,$+,$~,$=in zsh.\$/is specified by POSIX where the backslash is required to escape the$. – Stéphane Chazelas Mar 06 '23 at 15:09