batmancn
batmancn

Reputation: 477

When should I use "" to quote a value in shell test and in echo?

I'm writing bash script like this:

VF_ETH=$(command)
if [ -n "$VF_ETH" ] ; then
    echo "ixgbevf eth: "$VF_ETH
fi

command is a linux command, my question is:

  1. $VF_ETH is to get value of VF_ETH, why use "" to quote it in line2 in shell test?
  2. if I do not use "" to quote it, will test failed?
  3. if use "" to quote a value is to make it into string, why not use in echo in line3?

Thank you

Upvotes: 1

Views: 1230

Answers (3)

janos
janos

Reputation: 124714

You should always double quote variables used in command line arguments and within [ ... ] tests, for example:

ls "$var"
echo "$var"
[ -f "$var" ]
test -f "$var"

In all the above examples the commands used will receive different values with and without the double quotes, when the value of $var starts with a bunch of spaces and contains some spaces. For example:

var=" an apple"
echo "$var"  # prints " an apple"
echo $var    # prints "an apple", without the leading space

You don't need to quote them in simple assignments, for example:

a=$var
a=$var$b

If the assignment contains spaces or other special characters, then you have to quote, or escape those special characters:

a="$var $b"
a=$var\ $b
a=$var" "$b

All the above are equivalent, but the first one is probably the easiest to read, and therefore recommended.

You don't need to quote special variables that never have unsafe values, for example:

test $? = 0

If you're unsure, or not yet confident, then a good role of thumb is to double quote always.

Upvotes: 2

Utsav
Utsav

Reputation: 8103

Assuming you get an actual command stored in VF_ETH variable, which contains spaces. Now if you use if [ -n $VF_ETH ] and when shell expands the variable, there will be multiple parameters to -n whereas it expects only one. Hence you might get something like binary operator expected error.

Also in the echo command, it is not mandatory to have only one parameter. Hence even if you are not using double quotes, it works.

Hence to avoid it, always use double quotes while expanding variables.

Also use https://www.shellcheck.net/ to check your script and it will give you correct information on where your script is wrong/not as per standard.

Upvotes: 2

James Brown
James Brown

Reputation: 37424

For 1. and 2. If you set $VF_ETH="x -a -z x" and test it with code:

if [ -n $VF_ETH ] ; then
  echo yes 
else 
  echo nope
fi

the output will be nope as the the inside of the square brackets would expand to -n x AND -z x (nonempty and empty). Adding quotes around the variable would fix that.

  1. Set $VF_ETH="*". Now if you echo $foo bash would do wildcard expansion and echo would output the contents of your current directory.

Upvotes: 0

Related Questions