本文介绍了如何在 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.
推荐答案使用 "$@" 表示所有参数:
Use "$@" to represent all the arguments:
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 脚本中迭代参数
发布评论