example
while [ -n "$1" ]
do
something
done
can i write $1
instead of "$1"
? And what is the difference between
user=alexander
and user="alexander"
? Thanks
example
while [ -n "$1" ]
do
something
done
can i write $1
instead of "$1"
? And what is the difference between
user=alexander
and user="alexander"
? Thanks
$ var="two words"
$ function num_args() { echo "${#}"; }
$ num_args $var
2
$ num_args "$var"
1
The difference between $A and "$A" is how word breaks are treated with respect to passing arguments to programs and functions.
Imagine script that works on files (let's say moves them around):
$ cat my-move
#! /bin/sh
# my-move
src=${1}
dst=${2}
# ... do some fancy business logic here
mv ${src} ${dst}
$ my-move "some file" other/path
As the code stands now (no quotes) this script is broken as it will not handle file paths with spaces in them correctly.
(Following thanks to @CharlesDuffy)
Additionally quoting matters when handling glob patterns:
$ var='*'
$ num_args "$var"
1
$ num_args $var
60
Or:
$ shopt -s failglob
$ var='[name]-with-brackets'
$ echo $var
bash: no match: [name]-with-brackets
$ echo "$var"
[name]-with-brackets
The quotes act as a way to group the argument regardless of the presence of spaces or other special characters. By way of demonstration, here's a case where the two are materially different:
$ foo="bar baz"
$ sh -c 'echo $1' worker $foo
bar
$ sh -c 'echo $1' worker "$foo"
bar baz
In the above example we pass $foo
without quotes, which passes bar
as argument 1 and baz
as argument two, but when we pass it with quotes it passes bar baz
as argument 1.
So while you can write a variable without quotes (e.g. $1
), it is generally best practice to wrap it in quotes, unless you are specifically looking for it to be potentially treated as several independent arguments.