如何在 bash 脚本中将通配符与 getopts 一起使用?

发布于 2024-12-29 07:57:30 字数 736 浏览 2 评论 0原文

我有一个 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 run
getopts_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

另类 2025-01-05 07:57:30

在执行脚本之前,通配符模式会由 bash 展开。不是解释脚本的 shell,而是运行脚本的 shell。它是否保持模式、不传递任何内容或失败取决于 nullglobfailglob 和一些此类选项(请参阅 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 on nullglob, failglob and some such options (see man bash).

Also, in for file in "$fileList" quotes explicitly tell shell not to expand the variable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文