我无法理解为什么我的shell脚本输出以下内容,我想知道是否有人可以解释发生了什么。
脚本:
#!/bin/bash
thisCommand="echo"
thatCommand="echo"
LOGPATH=bar
ID=foo
thisCommand="$thisCommand \$(ls -1t $LOGPATH/$ID* )"
ID=random
thatCommand="$thatCommand \$(ls -1t $LOGPATH/$ID* )"
echo $thisCommand
echo $thatCommand
输出:
echo $(ls -1t bar/foo345 bar/foo346 )
echo $(ls -1t bar/random* )
bar/foo345
和bar/foo346
存在但bar/random*
没有。
所以这里的通配符只会与实际文件一起复制(如果存在)。 shell脚本不应该只是坚持使用通配符还是替换flie名称,如果它不存在则抛出错误?
答案 0 :(得分:3)
您可以使用shopt
命令更改此行为:
shopt -s nullglob
对于某些无法扩展的glob模式,它不会回显*
。
根据BASH手册:
nullglob
如果设置,bash允许不匹配任何文件的模式(请参阅 上面的路径名扩展)扩展为null 字符串,而不是自己。
答案 1 :(得分:1)
如果引用参数扩展,则不会尝试生成文件名:
$ echo "$thisCommand"
echo $(ls -1t bar/foo* )