#!/bin/bash
# This question is from advanced bash scripting guide section 5.1
echo
var="'(]\\{}\$\""
IFS='\'
echo $var
# output is '(] {}$"
# \ converted to space. Why?
echo "$var"
# output is '(]\{}$"
# special meaning of \ used, \ escapes \ $ and " RIGHT?
echo
var2="\\\\\""
echo $var2
# output is "
# \ converted to space. Why?
echo
# But ... var2="\\\\"" is illegal. Why?
var3='\\\\'
echo "$var3" # \\\\
# Strong quoting works, though. Why?
Asked
Active
Viewed 3,188 times
1

codeforester
- 39,467
- 16
- 112
- 140

Ankur Agarwal
- 23,692
- 41
- 137
- 208
-
Please format your question so we can understand it. – Carl Norum Mar 30 '11 at 22:28
-
Sorry, but what do you not understand ? How is the formatting incorrect ? – Ankur Agarwal Mar 30 '11 at 22:28
-
it's unclear what parts of your post are your questions and what parts are the script. Not to mention large parts of the script aren't formatted at all. – Carl Norum Mar 30 '11 at 22:30
1 Answers
3
IFS='\' echo $var # o/p is '(] {}$" # \ converted to space. Why?
Because you told the shell that a backslash is a field separator and since you did not quote $var
when you echo'd it out, it was subject to word splitting based on IFS.
echo "$var" # o/p is '(]\{}$" # special meaning of \ used, \ escapes \ $ and " RIGHT ?
Here you quoted $var
and thus no word splitting will be performed on it. Your output is exactly what you told the shell var
was equal to. i.e. '(]\{}$"
var2="\\\\\"" echo $var2 # o/p is " # \ converted to space. Why?
See first answer
# But ... var2="\\\\"" is illegal. Why?
Because every pair of backslashes makes up a literal backslash and there is no backslash left over to escape out the 2nd double quote. The shell doesn't know what to do with 3 double quotes.
echo "$var3" # \\\\ # Strong quoting works, though. Why ?
See second answer about word splitting
Note that you could also use the string literal syntax $''
vis var=$'\'(]\{}$"'
which would only require you to escape out the single quote

SiegeX
- 135,741
- 24
- 144
- 154
-
I am still confused. Why is \ before $ and " not converted to space on doing echo $var ? – Ankur Agarwal Mar 31 '11 at 00:29
-
@abc: Because `\ ` by itself is not a character but syntax to signify an escape sequence. So `\$` and `\"` is telling the shell you want a literal `$` and a literal `"`. It is necessary to escape these because `$` by itself has special meaning to the shell and you must escape the double-quote because you've surrounded `var`'s value with double-quotes. It is only `\\ ` which is a literal backslash which is subsequently counted by a field separator – SiegeX Mar 31 '11 at 04:10