Escaping strings in Bash
A couple of days ago, an interesting thread came up on HN about escaping strings in Bash using !:q.
As Pascal Hirsch describes on Twitter,
the idea is simple: after an expression, use !:q to escape the given string.
Useful when you need to pass a complex string as a single quoted argument, or when constructing safe inputs for commands like xargs, ssh, or eval.
$ # 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.
Print without executing
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 $'