1
#!/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?
3
  • Please format your question so we can understand it. Commented Mar 30, 2011 at 22:28
  • Sorry, but what do you not understand ? How is the formatting incorrect ? Commented Mar 30, 2011 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. Commented Mar 30, 2011 at 22:30

1 Answer 1

4
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

Sign up to request clarification or add additional context in comments.

2 Comments

I am still confused. Why is \ before $ and " not converted to space on doing echo $var ?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.