问题描述
我的同事,瑞安,来找我在他的Bash脚本中的错误,并且我与这个测试的问题:
My colleague, Ryan, came to me with a bug in his Bash script, and I identified the problem with this test:
$ mkdir ryan
$ mkdir ryan/smells-bad
$ FOO=ryan/smells-*
$ echo $FOO
ryan/smells-bad
$ touch $FOO/rotten_eggs
touch: cannot touch `ryan/smells-*/rotten_eggs': No such file or directory
由此我推断,通配echo命令过程中会发生,而不是在创建变量FOO。
From this I infer that the globbing happens during the echo command, not when the variable FOO is created.
我们有几个解决方法,按降序ungracefulness顺序:
We have a couple of workarounds, in descending order of ungracefulness:
touch `echo $FOO`/rotten_eggs
或者
pushd
cd $FOO
touch rotten_eggs
popd
但也不是令人满意的。我缺少一个把戏?
But neither is satisfying. Am I missing a trick?
推荐答案
的问题是,水珠就会仅在文件rotten_eggs的存在,展开,因为它包括在水珠图案。您应该使用数组。
The problem is that the glob will only expand if the file "rotten_eggs" exists, because it is included in the glob pattern. You should use an array.
FOO=( ryan/smells-* )
touch "${FOO[@]/%//rotten_eggs}"
该FOO数组包含一切的水珠匹配。使用%扩展追加/ rotten_eggs每个元素。
The FOO array contains everything matched by the glob. The expansion using % appends /rotten_eggs to each element.
这篇关于指定通配的结果在Bash中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!