如何在 Bash 脚本中迭代位置参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1769140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate over positional parameters in a Bash script?
提问by Sharat Chandra
Where am I going wrong?
我哪里错了?
I have some files as follows:
我有一些文件如下:
filename_tau.txt
filename_xhpl.txt
fiename_fft.txt
filename_PMB_MPI.txt
filename_mpi_tile_io.txt
I pass tau, xhpl, fft, mpi_tile_ioand PMB_MPIas positional parameters to script as follows:
我将tau, xhpl, fft,mpi_tile_io和PMB_MPI作为位置参数传递给脚本,如下所示:
./script.sh tau xhpl mpi_tile_io fft PMB_MPI
I want grep to search inside a loop, first searching tau, xhpl and so on..
我希望 grep 在循环内搜索,首先搜索 tau、xhpl 等等。
point= #initially points to first parameter
i="0"
while [$i -le 4]
do
grep "$str" ${filename}${point}.txt
i=$[$i+1]
point=$i #increment count to point to next positional parameter
done
回答by Steve K
Set up your for loop like this. With this syntax, the loop iterates over the positional parameters, assigning each one to 'point' in turn.
像这样设置你的 for 循环。使用此语法,循环遍历位置参数,依次将每个参数分配给“点”。
for point; do
grep "$str" ${filename}${point}.txt
done
回答by Paused until further notice.
There is more than one way to do this and, while I would use shift, here's another for variety. It uses Bash's indirection feature:
有不止一种方法可以做到这一点,虽然我会使用shift,但这是另一种多样化的方法。它使用 Bash 的间接功能:
#!/bin/bash
for ((i=1; i<=$#; i++))
do
grep "$str" ${filename}${!i}.txt
done
One advantage to this method is that you could start and stop your loop anywhere. Assuming you've validated the range, you could do something like:
这种方法的一个优点是您可以在任何地方开始和停止循环。假设您已经验证了范围,您可以执行以下操作:
for ((i=2; i<=$# - 1; i++))
Also, if you want the last param: ${!#}
另外,如果你想要最后一个参数: ${!#}
回答by Alberto Zaccagni
回答by Bobby
Try something like this:
尝试这样的事情:
# Iterating through the provided arguments
for ARG in $*; do
if [ -f filename_$ARG.txt]; then
grep "$str" filename_$ARG.txt
fi
done
回答by ghostdog74
args=$@;args=${args// /,}
grep "foo" $(eval echo file{$args})

