Bash tips 03: the importance of double quotes

Time:2021-4-23

Suppose in a bash script, the functionfooIt is defined as follows:

function foo {
    echo ">> $1 ..."
    echo ">> $2 ..."
}

Call foo:

foo "" "test"

That is, empty strings and"test"Call for parameter valuefooThe results are as follows

>>>  ...
>>> test ...

Now let’s say there’s a functionbar, which is defined as follows

function bar {
    foo $1 $2
}

Then callbar

bar "" "test"

Result output

>>> test ...
>>>  ...

as a result of,barThe first parameter value it accepts is an empty string, but when it passes this parameter value to thefooBash no longer considers this parameter value to be an empty string, but treats it as an empty string$IFS——Field separator, sofoofrombarOnly one parameter value is obtained here"test"And treat it as its first parameter value.

As a matter of fact, not only is empty string easy to cause trouble, but if there is a space in the parameter value, it will also cause troublebarIt’s hard to predict.

barThe correct definition is as follows:

function bar {
    foo "$1" "$2"
}

Therefore, when writing bash script, if you are not sure whether the function parameter value is empty string or contains spaces, you should not hesitate to surround it with double quotation marks. Single quotation marks are not allowed because bash variables cannot be expanded in single quotation marks.