Issue
Hi I'm new to shell scripting in csh and I need help with an annoying problem. 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.
Solution
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).
Since i
(for "iteration") is sort-of the standard name for this, I renamed your $i
to $v
for "value".
As a final note, you probably don't want to use csh
for scripting if it can be avoided. It has many problems and limitations.
Answered By - Martin Tournoij Answer Checked By - Mildred Charles (WPSolving Admin)