brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: printf %q quotes a string so the shell can read it back safely

Shell
~/tips/tip-shell-printf-q-quote-for-reuse

printf '%q\n' "$name"

Prints a value with escaping, so spaces and special characters survive when it is pasted back into a shell command.

File names with spaces, quotes or a dollar sign in them are where my shell scripts get fragile. Bash has a built-in way to print such a value in a form that is safe to use again.

name='my file (final) $1.txt'
printf '%q\n' "$name"

The Bash manual describes %q as an extra printf format that outputs the argument in a format that can be reused as shell input. It uses backslash quoting, or the ANSI-C $'...' style when a character like a newline needs it. The output of the example is my\ file\ \(final\)\ \$1.txt.

That is useful when a script has to build a command line as text, for instance to print a command for someone to copy, to write it to a log, or to pass it through ssh:

ssh server "ls -l $(printf '%q' "$name")"

Without the quoting, the remote shell would split the name at the spaces and try to interpret the parentheses and the dollar sign.

Two caveats. First, %q belongs to the Bash builtin printf, so the result can differ in sh, dash or on a system where /usr/bin/printf gets called instead. The GNU coreutils version has a similar directive, but check it. Second, a bug-bash thread points out that %q does not escape every character, such as a tilde, in all cases, so do not treat it as a security boundary for untrusted input. For that, pass values as arguments or through a quoted array instead of building strings.

Further reading: Bash manual: bash builtins

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link