我对这些运算符在 bash 中使用时有何不同(括号、双括号、括号和双括号)感到有些困惑。
[[ , [ , ( , ((
Run Code Online (Sandbox Code Playgroud)
我见过人们在这样的 if 语句中使用它们:
if [[condition]]
if [condition]
if ((condition))
if (condition)
Run Code Online (Sandbox Code Playgroud) 我对使用单括号或双括号感到困惑。看看这段代码:
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}"以防止空格引起的问题?