Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

bash - 如何在Bash脚本中迭代参数(How to iterate over arguments in a Bash script)

I have a complex command that I'd like to make a shell/bash script of.

(我有一个复杂的命令,我想制作一个shell / bash脚本。)

I can write it in terms of $1 easily:

(我可以轻松地用$1来写它:)

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.

(当然,我想处理其中包含空格的文件名。)

  ask by Thelema translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...