Quoting vs not quoting the variable on the RHS of a variable assignment

后端 未结 5 1692
孤街浪徒
孤街浪徒 2020-12-16 14:12

In shell scripting, what is the difference between these two when assigning one variable to another:

a=$b

and

a=\"$b\"
         


        
5条回答
  •  难免孤独
    2020-12-16 14:51

    Here are some other examples: ( having two files in the current directory t.sh and file)

    a='$(ls)'        # no command substitution
    b="$(ls)"        # command substitution, no word splitting
    c='*'            # no filename expansion
    d="*"            # no filename expansion
    e=*              # no filename expansion
    f=$a             # no expansions or splittings
    g="$a"           # no expansions or splittings
    h=$d             # no expansions or splittings
    
    echo ---'$a'---
    echo $a          # no command substitution
    echo ---'$b'---
    echo $b          # word splitting
    echo ---'"$b"'---
    echo "$b"        # no word splitting
    echo ---'$c'---
    echo $c          # filename expansion, word splitting
    echo ---'"$c"'---
    echo "$c"        # no filename expansion, no word splitting
    echo ---'$d'---
    echo $d          # filename expansion, word splitting
    echo ---'"$d"'---
    echo "$d"        # no filename expansion, no word splitting
    echo ---'"$e"'---
    echo "$e"        # no filename expansion, no word splitting 
    echo ---'$e'---
    echo $e          # filename expansion, word splitting
    echo ---'"$f"'---
    echo "$f"        # no filename expansion, no word splitting 
    echo ---'"$g"'---
    echo "$g"        # no filename expansion, no word splitting
    echo ---'$h'---
    echo $h          # filename expansion, word splitting
    echo ---'"$h"'---
    echo "$h"        # no filename expansion, no word splitting
    

    Output:

    ---$a---
    $(ls)
    ---$b---
    file t.sh
    ---"$b"---
    file
    t.sh
    ---$c---
    file t.sh
    ---"$c"---
    *
    ---$d---
    file t.sh
    ---"$d"---
    *
    ---"$e"---
    *
    ---$e---
    file t.sh
    ---"$f"---
    $(ls)
    ---"$g"---
    $(ls)
    ---$h---
    file t.sh
    ---"$h"---
    *
    

    One interesting thing to notice is that command substitution occurs in variable assignments if they are in double quotes, and if the RHS is given explicitly as "$(ls)" and not implicitly as "$a"..

提交回复
热议问题