如何从命令行读取 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/*
、4
和 gz
是命令行参数)。当我尝试上面的脚本时,它只读取第一个文件。有什么想法吗?
最佳答案
您需要访问传递给脚本的参数的所有内容。在执行脚本之前,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/