printf as a bash builtin vs an executable (behavior differences)
2
votes
4
answers
914
views
I am trying to better understand
printf
so I read multiple pages on this command, but I also stumbled upon different behavior of %q
directive. Namely, stated on this page :
> What is the difference between printf
of bash shell, and /usr/bin/printf
? The main difference is that the bash built-in printf
supports the %q
format specifier, which prints escape symbols alongside characters for safe shell input, while /usr/bin/printf
does not support %q
.
***
It behaves different, but I may not fully understand what the sentence means. The following is *different*, yet I think equally effective:
info printf | grep -A 4 '%q'
> An additional directive %q
, prints its argument string in a format that can be reused as input by most shells. Non-printable characters are escaped with the POSIX proposed $''
syntax, and shell metacharacters are quoted appropriately. This is an equivalent format to ls --quoting=shell-escape
output.
$ touch 'printf testing %q.delete'
# no output
$ \ls -l printf\ testing\ %q.delete
-rw-rw-r-- 1 vlastimil vlastimil 0 Jun 15 23:21 'printf testing %q.delete'
$ /usr/bin/printf '%q\n' printf\ testing\ %q.delete
'printf testing %q.delete'
$ printf '%q\n' printf\ testing\ %q.delete # Bash builtin
printf\ testing\ %q.delete
***
Can anyone elaborate on these differences, maybe adding in which scenarios it is advised to use this or that one? Thank you.
Asked by Vlastimil Burián
(30505 rep)
Jun 15, 2025, 10:40 PM
Last activity: Jun 22, 2025, 03:04 AM
Last activity: Jun 22, 2025, 03:04 AM