gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 11:46:35 26 4
gpt4 key购买 nike

我想显示通过参数提供给我的 shell 脚本的文件内容。我需要使用普通的“for (())”循环而不是“for x in arr”循环来执行此操作。

这是我的代码。我应该如何为该 cat 命令正确输入文件名?

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

最佳答案

你可以使用类似的东西:

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

对应的手册部分:

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; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

关于linux - 在 shell 脚本中使用 for 循环遍历参数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10061071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com