Is there a reason not to specify variables?

Is there a good reason not to put all variables in the shell of the script in quotation marks? ("I don't know anything better," in my opinion, is not a good reason.)

Generally speaking, quoted variables make sure that they are treated as one variable if they contain spaces or other special characters. So, why did anyone ever go for the “unsafe” way, and not with quotation variables?

+4
source share
4 answers

So why would anyone go for the "unsafe" way and not for a quote? variables?

. . :

1. .

:

glob=*.xml
# Do something, possibly creating xml files
rm $glob

glob , , rm. , .

bash glob=(*.xml). , , , , .

2. .

, POSIX, :

opts=
[ -f "$onething" ] && opts="-a"
[ -f "$another" ] && opts="$opts -b"
cmd $opts

cmd . $opts , .

. bash opts , , . POSIX , , , .

3. Bash [[

[[...]] , = glob. , :

$ glob=*.xml
$ [[ file.xml = "$glob" ]] && echo yes
$ [[ file.xml = $glob ]] && echo yes
yes

, . , . , glob, .

, , =~ :

$ regex=fi.*ml
$ [[ file.xml =~ "$regex" ]] && echo yes
$ [[ file.xml =~ $regex ]] && echo yes
yes

( : )

+10

, " , script " → < < , , .

, , CAN NOT ; .

   COUNT=1
   FILENAME=file$COUNT.txt

, , ; .

   echo the filename is $NAME 

"" ( , ), , .


, , , , ; .

+1

TL; DR

for-loops, . .

, @ . :

foo=(bar baz quux)
for word in "${foo[@]}"; do
    echo "$word"
done

, (, PATH MANPATH) , , ${MANPATH//:/ }:

MANPATH=/usr/share/man:/usr/local/share/man

# Replace colons with spaces to create list.
for path in ${MANPATH//:/ }; do
    echo "$path"
done

MANPATH, . "${MANPATH//:/ }" , . , , .

+1

, : "$variable" ...
/ " ": "$( ls )" , , " ": "$(( 2+2 ))".
, , .

, , :

1. : var=$oldvar.

, $oldvar , : " value oldvar.

, , , , :

var=a var with spaces                # Clearly will fail.
var="a var with spaces"              # It MUST be quoted to work.

() , IMhO:

var="$oldvar"

2. / .

echo $var var='/home/user/*/', /home/user/.

3. / .

    echo $(ls -d directory/*)

, .
. :

    echo $(seq 1 10)

, , .

4. / ( ).

case , .

var='*[0-9]*'    
case "$1" in
    $var) echo "has one digit (at least)";;

=, == !=: [[ $vara == $varb ]].
=~, , .

5. " ".

, unquoted var " ".

in: for var in $list.

var , " ". . $list, *, .

: set -- $var.
var='a variable with spaces', $1 a, $2 variable ..

set -- "$var", .
$1 'a variable with spaces'.

: $var, - set - $var. , , .

+1

Source: https://habr.com/ru/post/1608175/


All Articles