Tutorial 2) Part 3:  For-loops, Nested if-else statements

In programming, a for loop is a control flow statement specifying iteration over a list of objects that executes a block of code repeatedly. In the Unix C shell, the foreach routine is useful for operating on a set of data files. The loop iterates for each argument in parentheses, setting the variable equal to each filename found in parenthesis. The * wildcard can iterate over each file in your current directory:

touch list  # initialize file named list

foreach file (*)

  echo $file >> list

  end

cat list

Here a character string is being stored in the variable file during each iteration of the loop. The syntax for manually storing a string variable in C shell would be:

 set file=filename

 echo $file

 set str = fo g

 echo $str

 set str="fo g"  overwrite the str variable with a longer string

 echo $str

Q3:   Experiment with interchanging set and @ with successive addition operations as shown in the examples below. What happens and why?

 set i=3+4

 echo $i

 set i=$i+1

 echo $i

 @ i= $i + 1    because i is a string, we can't do integer arithmetic

@: Badly formed number.

 @ j = 10

 set j=$j+3

 echo $j

 set text=100

 @ text++ smart shells convert characters to an integer if possible

 echo $text