[英]Csh echo foreach loop index
Hi I'm new to shell scripting in csh and I need help with an annoying problem.嗨,我是 csh 中 shell 脚本的新手,我需要帮助解决一个烦人的问题。 Take the code below:拿下面的代码:
set s = ("one" "two" "three" "four")
foreach i (${s})
echo $i"-" [what do I put here to get the index?]
end
This yields the output这产生了输出
one-
two-
three-
four-
However, I would also like to print out the loop counter index too, so:但是,我也想打印出循环计数器索引,所以:
one-1
two-2
three-3
four-4
Sorry if this question is really basic but I don't have much experience in shell scripting (let alone csh) and forums and other stack-overflow posts didn't help much.对不起,如果这个问题真的很基础,但我在 shell 脚本(更不用说 csh)和论坛和其他堆栈溢出帖子方面没有太多经验并没有多大帮助。
You'll need to use a separate variable which you manually increment:您需要使用一个单独的变量,您可以手动递增:
set s = ("one" "two" "three" "four")
set i = 0
foreach v ( $s )
echo "$v - $i"
@ i = $i + 1
# Also works
#@ i++
end
You can do arithmetic by using the special @
command (the space between @
and i
is mandatory since this is a command, and not "syntax", you can actually use any expression here, not just arithmetic).您可以使用特殊的@
命令进行算术运算( @
和i
之间的空格是强制性的,因为这是一个命令,而不是“语法”,您实际上可以在这里使用任何表达式,而不仅仅是算术)。
Since i
(for "iteration") is sort-of the standard name for this, I renamed your $i
to $v
for "value".由于i
(表示“迭代”)是这个的标准名称,我将您的$i
重命名为$v
表示“值”。
As a final note, you probably don't want to use csh
for scripting if it can be avoided.最后要注意的是,如果可以避免的话,您可能不想使用csh
来编写脚本。 It has many problems and limitations.它有很多问题和局限性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.