如何遍历Bash脚本中的参数 [英] How to iterate over arguments in a Bash script
本文介绍了如何遍历Bash脚本中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个复杂的命令,我想用它编写一个shell/bash脚本.我可以很容易地用$1
来写:
I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of $1
easily:
foo $1 args -o $1.ext
我希望能够将多个输入名称传递给脚本.什么是正确的方法?
I want to be able to pass multiple input names to the script. What's the right way to do it?
当然,我想处理文件名中带有空格的内容.
And, of course, I want to handle filenames with spaces in them.
推荐答案
使用"$@"
表示所有参数:
for var in "$@"
do
echo "$var"
done
这将遍历每个参数并将其打印在单独的行上. $ @的行为与$ *相似,不同之处在于,如果用引号将参数括起来,则它们之间如果有空格,则会被正确分解:
This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:
sh test.sh 1 2 '3 4'
1
2
3 4
这篇关于如何遍历Bash脚本中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文