简体   繁体   English

在 shell 脚本中使用 for 循环遍历参数列表?

[英]Iterating through argument list using for loop in shell script?

I want to display the contents of the files supplied to my shell script via arguments. I need to do this using the normal 'for (())' loop and NOT the 'for x in arr' loop.我想显示通过 arguments 提供给我的 shell 脚本的文件的内容。我需要使用普通的“for (())”循环而不是“for x in arr”循环来执行此操作。

This is my code.这是我的代码。 How should i put the file name correctly for that cat command?我应该如何为该 cat 命令正确输入文件名?

for (( i=1;$i<=$#;i=$i+2 ))
do
    cat '$'$i   #display the contents of the file currently being traversed
done

You can use something like:你可以使用类似的东西:

for (( i=1;$i<=$#;i=$i+1 ))
do
    cat ${!i}  #display the contents of the file currently being traversed
done

The corresponding manual section:对应的手册部分:

If the first character of parameter is an exclamation point, a level of variable indirection is introduced.如果参数的第一个字符是感叹号,则引入了一层变量间接。 Bash uses the value of the variable formed from the rest of parameter as the name of the variable; Bash使用参数rest组成的变量值作为变量名; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself.然后扩展此变量,并在替换的 rest 中使用该值,而不是参数本身的值。 This is known as indirect expansion.这称为间接扩展。 The exceptions to this are the expansions of ${.prefix*} and ${.name[@]} described below.例外情况是下面描述的 ${.prefix*} 和 ${.name[@]} 的扩展。 The exclamation point must immediately follow the left brace in order to introduce indirection.感叹号必须紧跟在左大括号之后,以引入间接性。

The normal behavior of a for loop is to iterate over the arguments. To iterate over all arguments: for 循环的正常行为是遍历 arguments。要遍历所有 arguments:

#!/bin/sh -e
for x; do cat $x; done

You can modify that slightly to only operate on every other argument as you do in your example in many different ways.您可以稍微修改它以仅对每个其他参数进行操作,就像您在示例中以许多不同的方式所做的那样。 One possibility is:一种可能性是:

for x; do expr $(( i++ )) % 2 > /dev/null || cat "$x"; done

If you insist on using the non-standard form, you can use the ${,var} bashism which will fail in the great majority of shells, or you can use eval如果你坚持使用非标准形式,你可以使用 ${,var} bashism 这在绝大多数 shell 中都会失败,或者你可以使用eval

for (( i = 1; i <= $#; i += 2 ))
do
    eval cat '"$'$i\"
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM