Pony of Shadows

Queen of Truth & King of Practice


bash脚本中如何展开字符串包含的通配符

一般的语句中,通配符在使用它的那一行展开,但被双引号包括时不会展开。

  • 示例脚本1:
#!/bin/bash
ls ~/tmp/*a
ls "~/tmp/*a"
tmp_path="~/tmp"
string="${tmp_path}/*a"
echo "string=$string"
ls $string
  • 运行结果1:
ponyofshadows@equestria ~/p/p/doc (master)> bash test_wildcard.sh
/home/ponyofshadows/tmp/1a  /home/ponyofshadows/tmp/2a
ls: cannot access '~/tmp/*a': No such file or directory
string=~/tmp/*a
ls: cannot access '~/tmp/*a': No such file or directory
  • 示例脚本2:
ls ~/tmp/*a

echo "*** ()1 ***"
tmp_path1=~/tmp
string_list1=( ${tmp_path1}/*a )
ls "${string_list1[@]}" 
echo "*** ()2 ***"
tmp_path2="~/tmp"
string_list2=( ${tmp_path2}/*a )
ls "${string_list2[@]}" 
  • 运行结果2:
ponyofshadows@equestria ~/p/p/doc (master)> bash test_wildcard1.sh
/home/ponyofshadows/tmp/1a  /home/ponyofshadows/tmp/2a
*** ()1 ***
/home/ponyofshadows/tmp/1a  /home/ponyofshadows/tmp/2a
*** ()2 ***
ls: cannot access '~/tmp/*a': No such file or directory

使用eval展开字符串中的通配符

# eval 把字符串参数当作命令进行解释和执行
eval $cmd
  • 代码示例
#!/bin/bash
ls ~/tmp/*a
pattern="~/tmp/*a"
matched=( $(eval echo $pattern) )
ls "$pattern"
ls "${matched[@]}"
  • 运行结果
ponyofshadows@equestria ~/p/p/doc (master)> bash test_wildcard2.sh
/home/ponyofshadows/tmp/1a  /home/ponyofshadows/tmp/2a
ls: cannot access '~/tmp/*a': No such file or directory
/home/ponyofshadows/tmp/1a  /home/ponyofshadows/tmp/2a