bash - 在 Bash 中从命令行读取 glob

标签 bash glob

如何从命令行读取 Bash 中的 glob?我试过了,它只获取了 glob 中的第一个文件:

#!/bin/bash
shopt -s nullglob
FILES=$1
for f in $FILES
do
  echo "Processing $f file..."
  echo $f
done

假设我的脚本是 script.sh。我想这样调用它 sh script.sh/home/hss/* 4 gz (其中 /home/hss/*4gz 是命令行参数)。当我尝试上面的脚本时,它只读取第一个文件。有什么想法吗?

最佳答案

您需要访问传递给脚本的参数的所有内容。在执行脚本之前,shell 会扩展 glob。

你可以复制数组:

#!/bin/bash
FILES=("$@")
for f in "${FILES[@]}"
do
    echo "Processing $f file..."
    echo "$f"
done

或者直接迭代:

#!/bin/bash
for f     # equivalent to for f in "$@"
do
    echo "Processing $f file..."
    echo "$f"
done

或者使用shift:

#!/bin/bash
while (($# > 0))
do
    echo "Processing $1 file..."
    echo "$1"
    shift
done

关于bash - 在 Bash 中从命令行读取 glob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5063864/

相关文章:

c - glob(使用唯一前缀)是否比 readdir 更快?

bash - 相当于命令行中的 exit

bash - 在多个文件中按行号打印一系列行

bash:退出源脚本

bash - 在 Bash Shell 脚本中处理子字符串搜索中的空格

android - 在 Android 上缺少且不工作的 glob.c

php glob模式匹配任意数字

linux - 模式匹配在 bash 脚本中不起作用

bash - 启动另一个应用程序的脚本将在退出时将其关闭

linux - 如何在 Bash Shell 脚本的 while 语句中编写 if 语句?