Lesson 9

Date: 3/26/2014
Linux shell scripting tutorial
Linux for Engineering and IT Applications


Looping with for statement

  • Script scr4.sh
    #!/bin/bash
    for i in red white blue 
    do
            echo "$i is a color"
    done
    

  • Script backup-lots.sh
    #!/bin/bash
    for i in 0 1 2 3 4 5 6 7 8 9 ; do
            cp $1 $1.BAK-$i
    done
    
    Now create a file important_data with some numbers in it and then run ./backup-lots.sh important_data, which will copy the file 10 times with 10 different extensions. As you can see, the variable $1 has a special meaning--it is the first argument on the command-line. Note, watch for correct syntax:
    for i in 0 1 2 3 4 5 6 7 8 9 
    do
    ....
    done
    
    another correct alternative:
    for i in 0 1 2 3 4 5 6 7 8 9  ; do
    ....
    done
    


    Now modify the script:
    #!/bin/bash
    if [ "$1" = "" ] ; then
            echo "Usage: backup-lots.sh <filename>"
            exit
    fi
    for i in 0 1 2 3 4 5 6 7 8 9 ; do
            NEW_FILE=$1.BAK-$i
            if [ -e $NEW_FILE ]; then
                    echo "backup-lots.sh: **warning** $NEW_FILE"
                    echo "                already exists - skipping"
            else
                    cp $1 $NEW_FILE
            fi
    done
    

  • Looping over glob expressions
    #!/bin/bash
    for i in *.txt ; do
            echo "found a file:" $i
    done
    

    Note, the script above loops over all *.txt files in the current directory so you need to create several files with .txt extension in this exercise.

    #!/bin/bash
    for i in /usr/share/*/*.txt ; do
            echo "found a file:" $i
    done
    


  • Breaking out of the loops and continuing
    #!/bin/bash
    for i in 0 1 2 3 4 5 6 7 8 9 ; do
            NEW_FILE=$1.BAK-$i
            if [ -e $NEW_FILE ]; then
                    echo "backup-lots.sh: **error** $NEW_FILE"
                    echo "                already exists - exitting"
                    break
            else
                    cp $1 $NEW_FILE
            fi
    done
    
    which causes program execution to continue on the line after the done.

    The continue statement is useful for terminating the current iteration of the loop.
    #!/bin/bash
    for i in 0 1 2 3 4 5 6 7 8 9 ; do
            NEW_FILE=$1.BAK-$i
            if [ -e $NEW_FILE ] ; then
                    echo "backup-lots.sh: **warning** $NEW_FILE"
                    echo "                already exists - skipping"
                    continue
            fi
            cp $1 $NEW_FILE
    done
    



  • Take me to the Course Website