如何在 bash 脚本中将通配符与 getopts 一起使用?
我有一个 bash 脚本,我想采用一些可选的输入参数,后跟文件名或包含通配符的文件规范。
如果我跑 getopts_problem.sh -td *.txt
该脚本愉快地输出当前目录中的 .txt 文件列表:
文件是 readme.txt letter_to_editor.txt someotherfile.txt
如果我运行 getopts_problem.sh -td *.ABC 脚本输出
文件是*.ABC
当前目录下没有扩展名为“.ABC”的文件。由于某种原因,脚本将“*.ABC”解释为文件名。如何让脚本将“*.ABC”识别为要扩展的文件名表达式,而不是实际的文件名?代码如下:
# !/bin/sh
doDry=0
doTimestamp=0
while getopts ":dt" OPT;
do
case $OPT in
d ) doDry=1 ;;
t ) doTimestamp=1 ;;
? ) echo 'Bad options used. '
exit 1 ;;
esac
done
shift $(($OPTIND - 1))
fileList=$@
for file in "$fileList"
do
echo file is $file
done
exit 0
I have a bash script that I want to take some optional input arguments, followed by either a filename or a file specification containing wildcards.
If I rungetopts_problem.sh -td *.txt
the script happily outputs a list of .txt files in the current directory:
file is readme.txt letter_to_editor.txt someotherfile.txt
If I run getopts_problem.sh -td *.ABC
the script outputs
file is *.ABC
There are no files in the current directory with the extension ".ABC". For some reason, then, the script interprets "*.ABC" as a filename. How can I get the script to recognise "*.ABC" as a filename expression to be expanded, rather than an actual filename? The code is as follows:
# !/bin/sh
doDry=0
doTimestamp=0
while getopts ":dt" OPT;
do
case $OPT in
d ) doDry=1 ;;
t ) doTimestamp=1 ;;
? ) echo 'Bad options used. '
exit 1 ;;
esac
done
shift $(($OPTIND - 1))
fileList=$@
for file in "$fileList"
do
echo file is $file
done
exit 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在执行脚本之前,通配符模式会由 bash 展开。不是解释脚本的 shell,而是运行脚本的 shell。它是否保持模式、不传递任何内容或失败取决于
nullglob
、failglob
和一些此类选项(请参阅man bash
)。另外,在
for file in "$fileList"
引号中明确告诉 shell 不要 扩展变量。The wildcard patterns are expanded by
bash
before executing your script. Not the shell that interprets the script, but the one you run it from. And whether it keeps pattern, passes nothing or fails depends onnullglob
,failglob
and some such options (seeman bash
).Also, in
for file in "$fileList"
quotes explicitly tell shell not to expand the variable.