'How do I escape a series of backslashes in a bash printf?
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?
Solution 1:[1]
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: \\\\
Solution 2:[2]
printf
is a bash builtin. Look at help printf
:
printf [-v var] format [arguments] Formats and prints ARGUMENTS under control of the FORMAT.
You should pass the format and the argument. So add the format "%s\n"
before the argument:
printf "%s\n" "escaped slash: \\"
printf "%s\n" "2 escaped slashes: \\\\"
printf "%s\n" "3 escaped slashes: \\\\\\"
printf "%s\n" "4 escaped slashes: \\\\\\\\"
Output:
escaped slash: \ 2 escaped slashes: \\ 3 escaped slashes: \\\ 4 escaped slashes: \\\\
Solution 3:[3]
An additional note on what Cyrus said:
If you quote the printf
's ARGUMENT
with single quotes, you should save a lot of backslashes. For example,
printf "%s\n" 'escaped slash: \'
printf "%s\n" '2 escaped slashes: \\'
printf "%s\n" '3 escaped slashes: \\\'
printf "%s\n" '4 escaped slashes: \\\\'
outputs
1 escaped slash: \
2 escaped slashes: \\
3 escaped slashes: \\\
4 escaped slashes: \\\\
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Kevin |