How does IFS work in Bash?

2019-08-01 15:29发布

问题:

#!/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?

回答1:

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



标签: bash shell ifs