参数在删除引用时正常工作

Parameters work properly when remove their quoting

我对脚本中引用的冗长感到困惑。以我遵循的说明为例:

min_val=1
max_val=100
int=50
if [[ "$int" =~ ^-?[0-9]+$ ]]; then
    if [[ "$int" -ge "$min_val" &&  "$int" -le "$max_val" ]]; then
        echo "$int is within $min_val to $max_val."
    else
        echo "$int is out of range."
    fi
else
    echo "int is not an integer." >&2
    exit 1
fi

运行 来吧:

$ bash test_integer3.sh
50 is within 1 to 100.

当我在测试中删除所有引用时:

if [[ $int =~ ^-?[0-9]+$ ]]; then
    if [[ $int -ge $min_val &&  $int -le $max_val ]]; then
        echo "$int is within $min_val to $max_val."
    else
        echo "$int is out of range."
    fi
else
    echo "int is not an integer." >&2
    exit 1
fi

它仍在正常工作。

$ bash test_integer3.sh
50 is within 1 to 100.

为什么要养成重复引用的习惯?

引号用于停止分词。在上面的情况下没有必要,但考虑这样的情况:你有一个目录和这些文件 file1.txtfile2.txtold.txtfile1 old.txt.
如果你想删除文件 file1 old.txt 和 运行 命令

rm file1 old.txt  

然后它将删除文件 old.txt 而不是您所期望的。

当您开始在脚本中使用 [ 命令而不是 [[ 时,真正的问题就来了。 [[ 是 bash 对 [ 命令的改进。它有几项增强功能,使其成为编写针对 bash.

的脚本的更好选择

其中一项改进是您不再需要引用变量,因为 [[ 可以更直观地处理空字符串和带有 white-space 的字符串。例如,考虑为 un-quoted 情况使用 [ 编写的脚本,并且为了讨论起见,您的一个变量是空的

#!/usr/bin/env bash

min_val=
max_val=
int=50

if [[ $int =~ ^-?[0-9]+$ ]]; then
    if [ $int -ge $min_val -a  $int -le $max_val ]; then
        echo "$int is within $min_val to $max_val."
    else
        echo "$int is out of range."
    fi
else
    echo "int is not an integer." >&2
    exit 1
fi

需要注意的一件事是我 re-written 使用 -a 语法的组合条件,因为 [ 不支持 && 运算符,但可以使用&& 作为 [ $int -ge $min_val ] && [ $int -le $max_val ]

你会看到事情变坏并看到如下错误,意味着涉及 -le 的条件之一在看到空字符串时出错。

1_script.sh: line 7: [: -a: integer expression expected
50 is out of range.

而对于未定义的变量使用相同的代码并将表达式替换为使用 [[ 将优雅地处理空字符串以产生不正确的结果,如

50 is out of range.

所以总而言之,从使用 [[ 的诸多优势来看,你的案例的特殊优势是在你的条件中可能有空字符串时处理变量。

在您的代码中,您发现不需要引号。但是,使用引号被视为 "good practice",因为没有引号可能会发生意想不到的事情。例如,如果您 运行 int 等于 "foo bar" 的代码,您可能会得到一些没有引号的奇怪结果。 它就像 JavaScript 中的 double and triple equals。您可能只使用双等号就可以逃脱,但可能会出现一些意想不到的结果。