如何在 Bash 脚本中迭代参数 [英] How to iterate over arguments in a Bash script

查看:32
本文介绍了如何在 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 脚本中迭代参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆