简体   繁体   English

在bash shell脚本中使用i作为变量

[英]Using i as a variable in bash shell script

I am trying to create a shell script that will take command line arguments and create one or more files based off of that. 我正在尝试创建一个将使用命令行参数并基于此创建一个或多个文件的shell脚本。 I know that each command line argument is stored in $0, $1, $2...and so on, so that is what this loop is based on. 我知道每个命令行参数都存储在$ 0,$ 1,$ 2 ...等中,因此这是此循环的基础。

for i in $(eval echo {1..$#})
do
    echo "File I'm about to edit/create: "$i""
    touch "$i"
done

However, $i is being taken literally as the number 1, 2..rather than the value in $1. 但是,$ i实际上是数字1、2 ..而不是$ 1中的值。

You would need to use indirect parameter expansion: 您将需要使用间接参数扩展:

echo "File...: ${!i}"
touch "${!i}"

However, it's much simpler to just iterate over the arguments themselves: 但是,仅遍历参数本身要简单得多:

for f in "$@"; do
    echo "File...: $f"
    touch "$f"
done

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

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