我对使用单括号或双括号感到困惑。看看这段代码:
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}"
以防止空格引起的问题?
根据test(1)
手册页:
-n STRING
the length of STRING is nonzero
Run Code Online (Sandbox Code Playgroud)
所以我预计这会运行良好:
-n STRING
the length of STRING is nonzero
Run Code Online (Sandbox Code Playgroud)
我在实际案例中使用了这个逻辑,脚本如下:
[ -n ${var} ] && echo "var is not empty"
Run Code Online (Sandbox Code Playgroud)
这里重要的是,当我运行它时,我收到以下消息:
DEBUG: in-loop peopkg:
DEBUG: in-loop wc -c: 0
DEBUG: in-loop test -n: true
DEBUG: wc -c: 0
DEBUG: pdir: a/alsa-firmware
Error: alsa-utils: doesn't exist in local repos
Run Code Online (Sandbox Code Playgroud)
这对我来说毫无意义。DEBUG: pdir: a/alsa-firmware
表明循环始终在第一次迭代时退出。仅当 glob 模式 a/alsa* 与某些内容匹配并且 peopkg 的长度非零时才会发生这种情况。
PS:我正在努力兼容 POSIX。