处理 bash 中没有文件匹配的通配符

Afr*_*roz 2 bash array wildcards

我试图将目录中的文件读取到数组中,但即使文件不存在,它也会保存到数组中。如果文件名不存在,我想排除它。

a=(/tmp/nofileexists) && echo ${#a[@]} && echo ${a[@]}
1
/tmp/nofileexists
Run Code Online (Sandbox Code Playgroud)

路径可能包含通配符。

a=(/tmp/nofileexists*.pdf) && echo ${#a[@]} && echo ${a[@]}
Run Code Online (Sandbox Code Playgroud)

cuo*_*glm 5

当文件名扩展失败时,您可以使用nullglobforbash返回空字符串:

$ shopt -s nullglob
$ a=(/tmp/nofileexists*.pdf) && echo ${#a[@]} && echo ${a[@]}
0
<blank line>
Run Code Online (Sandbox Code Playgroud)

或使用failglob报告错误:

$ shopt -s failglob
$ a=(/tmp/nofileexists*.pdf) && echo ${#a[@]} && echo ${a[@]}
bash: no match: /tmp/nofileexists*.pdf
Run Code Online (Sandbox Code Playgroud)