Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 961
Charney Kaye Avatar asked Jul 04 '15 19:07

Charney Kaye


People also ask

How do I ignore special characters in Bash?

Note the % <percent-sign> character within the printf argument. We can ignore its special meaning by escaping it with another <percent-sign>: %%. This preserves the literal value.

How do you escape a colon in Bash?

In bash ; escape with '\'. You do not need to escape the colon; assuming the variable values are correct, quoting the expansions is the only thing that may make a difference.

How do you ignore a backslash in sed?

Use single quotes for sed and you can get away with two backslashes. echo "sample_input\whatever" | sed 's/\\/\//' Hopefully someone will come up with the correct explanation for this behavior.


1 Answers

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: \\\\
like image 110
Eugeniu Rosca Avatar answered Oct 18 '22 16:10

Eugeniu Rosca