简体   繁体   中英

Csh echo foreach loop index

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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