我对使用单括号或双括号感到困惑。看看这段代码:
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}"
以防止空格引起的问题?
格式良好的printf
通常有一个可以使用的格式:
$ var="Hello"
$ printf '%s\n' "$var"
Hello
Run Code Online (Sandbox Code Playgroud)
但是,不提供格式可能会产生什么安全隐患?
$ printf "$var"
Hello
Run Code Online (Sandbox Code Playgroud)
由于变量扩展被引用,应该不会有任何问题,不是吗?