How do I escape a series of backslashes in a bash printf?

Charney Kaye picture Charney Kaye · Jul 4, 2015 · Viewed 25.6k times · Source

The following script yielded an unexpected output:

printf "escaped slash: \\ \n"
printf "2 escaped slashes: \\\\ \n"
printf "3 escaped slashes: \\\\\\ \n"
printf "4 escaped slashes: \\\\\\\\ \n"

Run as a bash script under Ubuntu 14, I see:

escaped slash: \
2 escaped slashes: \ 
3 escaped slashes: \\ 
4 escaped slashes: \\

Err.. what?

Answer

Eugeniu Rosca picture Eugeniu Rosca · Jul 4, 2015

Assuming that printf FORMAT string is surrounded by double quotes, printf takes one additional level of expansion, compared to e.g. echo (both being shell builtin commands).

What you expect from printf can actually be achieved using single quotes:

printf '1 escaped slash:   \\ \n'
printf '2 escaped slashes: \\\\ \n'
printf '3 escaped slashes: \\\\\\ \n'
printf '4 escaped slashes: \\\\\\\\ \n'

outputs:

1 escaped slash:   \
2 escaped slashes: \\
3 escaped slashes: \\\
4 escaped slashes: \\\\