Shell Programming

Lesson Goals

What is a shell script?

Why use a shell script?

Executing Shell Scripts

Exercise: Create a simple shell script using the cat command and execute it
$ cd
$ mkdir bin
$ cd bin
$ cat > script1
date
<Ctrl>d
   Executing the script Example:     $ vi checkuser
Type  i to switch to vi's insert mode
Type in these lines:

echo users currently logged in:
who | awk '{print $1}' | grep $1

Press Esc to switch to vi's command mode
Type :wq and press Enter to save the file and exit vi

Fix the permissions so it will execute.
$ chmod 755 checkuser

Now execute your script.
$ ./checkuser your-login-name

Shell Logic Structures

Sequential Logic

Decision Logic: if / else

  • use conditions to test
  • values of variable,
  • existence of files,
  • status of command execution
  • The basic syntax is:
    if condition then
        statements
    elif condition then
        statements
    else
        statements
    fi
    Exercise: write a short script named test that contains these lines    Execute the script
    $ bash test
    Jon Doe
       Modify the script by removing the double quotes around $NAME
       What happens when you execute?
    $ bash test
    test.bash: [: too many arguments

    Decision making script with the if-then-else clause

    Exercise:  Create a script that will greet you based on the time of day Exercise:

    Decision Logic with if-elif-else

    Exercise:

    Looping Logic: for, while, and until

    Here is the basic while syntax:
    while condition
    do
        statement
        ...
    done
    until is very similar. Typically while is the better choice.
    until condition
    do
        statement
        ...
    done
    for loop Example: Another for example: while loop example: Counting sheep until you fall asleep
    !/bin/sh

    # Begin by initializing the two variables
    # sleep and sheep to 0.
    # Don't confuse the function sleep (which will
    # pause execution for a given number of seconds,
    # with the variable sleep. sleep=0
    sheep=0

    # As long as sleep is equal to 0 the
    # while loop will not exit
    # '-eq' is used for testing numbers
    # '=' is used for testing strings, in this case
    # the variable must be quoted
    # Note how the Bourne shell handles arithmetic expressions

    while [ $sleep -eq 0 ]
    do
        let sheep=sheep+1
        echo $sheep
    done

    Can you predict what will happen?

    Test operators

    string = pattern string matches pattern (can contain wildcards)
    string != pattern string does not match pattern
    stringA < stringB stringA comes before stringB in dictionary order
    stringA > stringB stringA comes after stringB in dictionary order
    exprA -eq exprB Arithmetic expressions are equal
    exprA -ne exprB Arithmetic expressions are not equal
    exprA -lt exprB exprA is less than exprB
    exprA -gt exprB exprA is greater than exprB
    exprA -le exprB exprA is less than or equal to exprB
    exprA -ge exprB exprA is greater than or equal to exprB
    Running a script in debugging mode
        $ sh -x myprog
        $ bash -x myprog
     
  • Or add this line to your shell program right after the #!/bin/sh:
  •     set -x

  • In debug mode, the output will look confusing because the shell will do the following:
  • It will print a plus (+) infront of each command being processed.

    Case Logic

    case expression in
        pattern1 )
            statements
            ;;
        pattern2 )
            statements
            ;;
        ...
    esac
    Code example:
    
    #!/bin/sh
    
    leave=no
    while [ $leave = no ]; do
       cat << END
         MAIN MENU
         1) Print current working directory
         2) List all files in current directory
         3) Print today's date and time
         x) Exit
       Please enter your selection $LOGNAME:
       END
    
       read selection
    
       case $selection in
          1) pwd
          ;;
          2) ls -l
          ;;
          3) date
          ;;
          x) leave=yes
          ;;
       esac
    done
    exit 0

    The read command

    Here is an example of catching signals to interrupt execution of a script.

    random

    Test your skills:

    Your company just purchased another company and you have been tasked with the job of creating a user account for all the employees from the new company. Fortunately, you know how to write shell scripts!

    The HR department has handed you a list of the new employees in the form of Lastname, Firstname. Write a program that creates new accounts for users based on this text file of names.

    The user account names should be composed of  their first initial followed by their last name. Truncate all account names to eight characters. The program should take input from the file of names provided by HR. You can use some of the code from the read example above. Your program should put all the new users in the group users.

    Sample input file:

    Doe, John
    Smith, Candy
    Notingham, Michael
    Example accounts generated from this file:
    jdoe
    csmith
    mnotingh
    The useradd command can be used to create the accounts. Remember to place all users in the users group and to truncate all account names to 8 characters. This assignment is the class project for this semester. In order to get full credit, all criteria must be met. The program must work. Turn in both a paper and floppy copy of your final script. You can program in either the bash, sh, or ksh shell.

    Hints:

    You can use awk or cut to extract single characters or groups of characters from a string.

    l=`echo $last | awk '{print substr($0,1,7)}'`
    l=`echo $last | cut -c 1-7`
     
  • These expressions will grab just the first character in a string and place it in the varible f:

  • f=`echo $first | cut -c 1-1`
    f=`echo $first | awk '{print substr($0,1,1)}'`
    Translate can be used to translate all characters to lowercase
    $ echo "My Life iS BusY" | tr  '[A-Z]' '[a-z]'
    my life is busy