A couple of days ago, An interesting thread came up on HN about escaping string in Bash using !:q.
As Pascal Hirsch describes on Twitter,
the idea is simple: after an expression, use !:q
to escape the given string.
$ # This string 'has single' "and double" quotes and a $
$ !:q
'# This string '\''has single'\'' "and double" quotes and a $'
bash: # This string 'has single' "and double" quotes and a $: command not found
How does this work?
It starts with the history expansion character !
(!cmd
expands to the last cmd
executed) followed by the quote modifier (:q
).
A clever use of history expansion and modifiers.
Command Not Found
The p
modifier will print the command without execution, avoiding the command not found
error.
$ !:q:p
'# This string '\''has single'\'' "and double" quotes and a $'
Get my latest posts and updates. Subscribe to my newsletter.