Thursday, May 25, 2017

what is the difference between $1 and "$1" in bash script?





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



Answer



$ 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

No comments:

Post a Comment