相关疑难解决方法(0)

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

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

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万
查看次数

没有左边的“如果”,方括号是什么意思?

据我所知,方括号通常用于将表达式括在 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)

shell bash

72
推荐指数
2
解决办法
9万
查看次数

标签 统计

bash ×2

ksh ×1

quoting ×1

shell ×1

test ×1