[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: quotes around a variable
From: |
Robert E. Griffith |
Subject: |
Re: quotes around a variable |
Date: |
Sat, 16 Apr 2022 10:47:50 -0400 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Thunderbird/91.7.0 |
Here are two rules that I follow that helped me...
1) even though an assignment will work even if unquoted, like...
var1=$var2
vs...
var1="$var2"
even if var2 contains spaces, there is no reason that you need to use or
remember that feature. If you always put quotes around "$var2" its
simple and always does what you expect.
2) I remember that an eye opening moment for me in writing bash scripts
was realizing that when you double quote parameters to a
function/commend call, you are ensured that you are passing that many
arguments even if some are empty. An example might make that more clear...
function foo() {
echo "first='$1'"
echo "second='$2'"
}
var1=""
var2="hello"
foo "$var1" "$var2"
foo $var1 $var2
With the double quotes around the arguments, 'hello' will be in the
second position ($2) and the first position ($1) will be empty, but
since var1 happens to be empty in this case, without quotes it wont take
up a position and 'hello' will (unexpectedly) be in the first position.
The lesson for me is that I always use double quotes around
function/command call positional arguments. Even if I am passing a
literal string that can not be empty, I put it in double quotes...
foo "blue" "$var2" # its never wrong to quote every positional argument so
its an easy rule to follow
For optional arguments I often purposely do not quote them...
function foo() {
[ "$1" == "-f" ] && { doSomething...; shift; }
echo "first='$1'"
echo "second='$2'"
}
forceFlag="-f" # lets say that forceFlag comes from somewhere and could be empty or
could contain "-f"
foo $forceFlag "$var1" "$var2"
Now if forceFlag is empty, it wont take up an argument position and var1
and var2 will be $1 and $2 as expected but if it contains "-f", it will
take up a position but because function foo follows the convention that
options are removed (shifted) before positional arguments are handled,
var1 and var2 will still be in the correct and predictable positions.
One more note on passing arguments to functions/commands ...
foo "${options[@]}" "position1" "position2"
Even though the "${options[@]}" term is double quoted, if the options
array is empty, it will not add any arguments. The quoted [@] expansion
will produce one token for each element in the array no matter what is
in each array element. Therefore if there are no elements, it produces
no output at all and it disappears.
--BobG
On 4/16/22 07:29, wilson wrote:
when doing bash script, I am somewhat confused that, when I should use
Double quotes around the variable, when I should use single quotes
around the variable, and when I don't need the quotes. can you help
give a guide?
Thank you.