相关疑难解决方法(0)

Bash 运算符 [[ vs [ vs ( vs ((?

我对这些运算符在 bash 中使用时有何不同(括号、双括号、括号和双括号)感到有些困惑。

[[ , [ , ( , ((
Run Code Online (Sandbox Code Playgroud)

我见过人们在这样的 if 语句中使用它们:

if [[condition]]

if [condition]

if ((condition))

if (condition)
Run Code Online (Sandbox Code Playgroud)

shell bash test

436
推荐指数
6
解决办法
19万
查看次数

为什么不带引号的带空格的参数扩展在双括号“[[”内起作用,而在单括号“[”内不起作用?

我对使用单括号或双括号感到困惑。看看这段代码:

dir="/home/mazimi/VirtualBox VMs"

if [[ -d ${dir} ]]; then
    echo "yep"
fi
Run Code Online (Sandbox Code Playgroud)

尽管字符串包含空格,但它工作得很好。但是当我将其更改为单括号时:

dir="/home/mazimi/VirtualBox VMs"

if [ -d ${dir} ]; then
    echo "yep"
fi
Run Code Online (Sandbox Code Playgroud)

它说:

./script.sh: line 5: [: /home/mazimi/VirtualBox: binary operator expected
Run Code Online (Sandbox Code Playgroud)

当我将其更改为:

dir="/home/mazimi/VirtualBox VMs"

if [ -d "${dir}" ]; then
    echo "yep"
fi
Run Code Online (Sandbox Code Playgroud)

它工作正常。有人可以解释发生了什么吗?什么时候应该在变量周围分配双引号,"${var}"以防止空格引起的问题?

bash ksh quoting test

106
推荐指数
3
解决办法
4万
查看次数

标签 统计

bash ×2

test ×2

ksh ×1

quoting ×1

shell ×1