如何在 Bash 脚本中迭代参数

编程入门 行业动态 更新时间:2024-10-27 18:21:20
本文介绍了如何在 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 脚本中迭代参数

本文发布于:2023-10-09 10:24:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1475478.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   参数   迭代   如何在   Bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!