#!/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?
-
Please format your question so we can understand it.Carl Norum– Carl Norum2011-03-30 22:28:00 +00:00Commented Mar 30, 2011 at 22:28
-
Sorry, but what do you not understand ? How is the formatting incorrect ?Ankur Agarwal– Ankur Agarwal2011-03-30 22:28:57 +00:00Commented 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.Carl Norum– Carl Norum2011-03-30 22:30:56 +00:00Commented Mar 30, 2011 at 22:30
1 Answer
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
2 Comments
\ 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