我对使用单括号或双括号感到困惑。看看这段代码:
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}"以防止空格引起的问题?
据我所知,方括号通常用于将表达式括在 if else 语句中。
但我发现方括号没有“if”,如下所示:
[ -r /etc/profile.d/java.sh ] && . /etc/profile.d/java.sh
Run Code Online (Sandbox Code Playgroud)
在下面的脚本中。
#!/bin/bash### BEGIN INIT INFO
# Provides: jbossas7
# Required-Start: $local_fs $remote_fs $network $syslog
# Required-Stop: $local_fs $remote_fs $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start/Stop JBoss AS 7
### END INIT INFO
# chkconfig: 35 92 1
## Include some script files in order to set and export environmental variables
## as well as add the appropriate executables to …Run Code Online (Sandbox Code Playgroud)