Loops in Scripts


For Loops
The format for for loops is:
   for variable in list-of-variables
   do
      commands
   done
For example, both of the following scripts print the numbers 1, 2, 3, and 4.
#!/bin/bash
# Steve Dannelly
# demo for loops

for index in 1 2 3 4
do
   echo $index
done
#!/bin/bash
# Steve Dannelly
# demo for loops

mylist="1 2 3 4"
for index in $mylist
do
   echo $index
done


While Loops
The format for while loops is:
   while [ condition ]
   do
      commands
   done
For example, the following script also prints the numbers 1, 2, 3, and 4.
#!/bin/bash
# Steve Dannelly
# demo of while loops

index=1
while [ $index -lt 5 ]
do
   echo $index
   index=`expr $index + 1`
done

Those strange backward single quotes, which are difficult to find on the keyboard, perform an operation, then returns the value of the operation. So, linecnt=`cat myfile | wc -l` fill the variable linecnt with the number of lines in the file myfile.


Assignment

For your next assignment, clean up your majors script by using a for loop instead of using brute force. For example, you will probably have something that looks like this in your new version
for index in "CSCI" "CIFS" "ACCT" "ENTR" "MGMT" "MKTG"

Your new script will likely be much shorter, which will make it easier to edit for the assignment after this one.