2016-10-07 56 views
1

在GNU bash版本3.2.57上,我看到使用declare打印数组变量和nullglob选项之间存在冲突。Nullglob打破数组声明打印

这两个似乎是非常无关的,但是当nullglob被启用时,这是故意的吗?

#!/bin/bash 

test() { 
    local FOO="xyz" 
    local BAR=("one" "two" "three") 
    declare -p FOO 
    declare -a -p BAR 
} 

echo $(test) 
shopt -s nullglob 
echo $(test) 
shopt -u nullglob 
echo $(test) 

输出:在所述中间线

declare -- FOO="xyz" declare -a BAR='([0]="one" [1]="two" [2]="three")' 
declare -- FOO="xyz" declare -a 
declare -- FOO="xyz" declare -a BAR='([0]="one" [1]="two" [2]="three")' 

注意,当nullglob被设置时,没有声明BAR被发射。

回答

2

问题不是nullglob但未引用echo命令。

如果你引用它,那么它应该很好地工作:

shopt -s nullglob 
echo "$(test)" 
declare -- FOO="xyz" 
declare -a BAR='([0]="one" [1]="two" [2]="three")' 

无报价壳试图为有输出许多水珠字符扩大test函数的输出。

nullglob被设置时,扩展失败并且没有为失败的glob表达式打印任何内容。

+1

啊,有趣。我没有意识到我需要引用'$()'。当我允许时,我会在几分钟内接受你的回答。谢谢! – rgov

1

通过不引用echo $(test)然后$(test)部分受路径名扩展。 declare -p的结果包含[]字符,这些字符是针对文件系统进行检查的。当设置了nullglob并且没有匹配的文件时,该单词被删除。

尝试设置shopt -s failglob以查看更详细的情况;缺少匹配的文件会导致错误。