相关疑难解决方法(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万
查看次数

不给 printf 使用格式会带来安全后果吗?

格式良好的printf通常有一个可以使用的格式:

$ var="Hello"
$ printf '%s\n' "$var"
Hello
Run Code Online (Sandbox Code Playgroud)

但是,不提供格式可能会产生什么安全隐患?

$ printf "$var"
Hello
Run Code Online (Sandbox Code Playgroud)

由于变量扩展被引用,应该不会有任何问题,不是吗?

shell security printf

15
推荐指数
2
解决办法
2930
查看次数

标签 统计

bash ×1

ksh ×1

printf ×1

quoting ×1

security ×1

shell ×1

test ×1