一般的语句中,通配符在使用它的那一行展开,但被双引号包括时不会展开。
#!/bin/bash
ls ~/tmp/*a
ls "~/tmp/*a"
tmp_path="~/tmp"
string="${tmp_path}/*a"
echo "string=$string"
ls $string
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
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[@]}"
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