bash - I just assigned a variable, but echo $variable shows something else -


here series of cases echo $var can show different value assigned. happens regardless of whether assigned value "double quoted", 'single quoted' or unquoted.

how shell set variable correctly?

asterisks

the expected output /* foobar free software */, instead list of filenames:

$ var="/* foobar free software */" $ echo $var  /bin /boot /dev /etc /home /initrd.img /lib /lib64 /media /mnt /opt /proc ... 

square brackets

the expected value [a-z], single letter instead!

$ var=[a-z] $ echo $var c 

line feeds (newlines)

the expected value list of separate lines, instead values on 1 line!

$ cat file foo bar baz  $ var=$(cat file) $ echo $var foo bar baz 

multiple spaces

i expected aligned table header, instead multiple spaces either disappear or collapsed one!

$ var="       title     |    count" $ echo $var title | count 

tabs

i expected 2 tab separated values, instead 2 space separated values!

$ var=$'key\tvalue' $ echo $var key value 

in of cases above, variable correctly set, not correctly read! right way use double quotes when referencing:

echo "$var" 

this gives expected value in examples given. quote variable references!


why?

when variable unquoted, will:

  1. undergo field splitting value split multiple words on whitespace (by default):

    before: /* foobar free software */

    after: /*, foobar, is, free, software, */

  2. each of these words undergo pathname expansion, patterns expanded matching files:

    before: /*

    after: /bin, /boot, /dev, /etc, /home, ...

  3. finally, arguments passed echo, writes them out separated single spaces, giving

    /bin /boot /dev /etc /home foobar free software desktop/ downloads/ 

    instead of variable's value.

when variable quoted will:

  1. be substituted value.
  2. there no step 2.

this why should always quote variable references, unless require word splitting , pathname expansion. tools shellcheck there help, , warn missing quotes in cases above.


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -