I’m studyng Bash, and I see that the form
C=example
echo "$C"
give the same result of the form
C="example"
echo $C
I’d like to know if is better put the " " in the assignment of the variable or after the $. Or if it is indifferent. or if one is consider "more beautiful" than the other.
If you’re certain that a variable’s value is a single word (no white space) then it’s OK to use
$varnameor${varname}. If you can’t guarantee this, then you should use"$varname"or"${varname}". Note that bash does word-splitting before interpreting your command, so you may actually get a syntax error if you don’t quote the expression, for examplewill result in syntax error:
while this works fine:
This is due to the fact after variable expansion in the first, unquoted case bash sees this:
and the
-zoperator expects just one, not two arguments. In the second, quoted case bash sees this:i.e. just a single argument as required. Note also that quotes were used in assignment
as it would also produce an error if you wrote
since this would mean: execute command
spacewith environment containing an added variableC=white.So, in general you should quote these expressions to ensure your code is more robust against unforeseen variable values. This is especially true if the variable value comes from input, file etc. It is usually safe to drop the quotes for integer variables or when you just want to display the value of a variable as in
echo $C.