Main index

Introducing UNIX and Linux


More on shells

Overview
Simple arithmetic
      Arithmetic expansion
            Operators for arithmetic expansion
      The 'expr' command
Pattern matching
      Patterns
            Examples of patterns
      The case statement
Entering and leaving the shell
More about scripts with options
Symbolic links
Setting up terminals
Conventions used in UNIX file systems
Summary
Exercises

Answer to chapter 8 question 7

This solution involves a moderately complex while loop.

# Check number of arguments
if   [ $# -ne 1 ]
then echo "Requires 1 argument"
     exit 1
fi

# Check the argument is between 1 and 15
case $1 in
   [1-9]|1[0-5])  ;;
   *)             echo "Require number 1-15"
                  exit 1
esac

LINE=1      # Use to count through the lines
while [ $LINE -le $1 ]
do
    # For the top and bottom lines of the square
    if [ $LINE -eq 1 ] || [ $LINE -eq $1 ]
    then   printf "+"     # First column
           COL=2          # Column to print in next
           while [ $COL -lt $1 ]
           do    printf "-"
                 COL=$(( $COL + 1 )
           done
           printf "+\n"   # Last column, and end line
    # The middle lines
    else   printf "|"     # First column
           COL=2          # Column to print in next
           while [ $COL -lt $1 ]
           do    printf " "
                 COL=$(( $COL + 1 )
           done
           printf "|\n"   # Last column, and end line
    fi
    LINE=$(( $LINE + 1 )
done

Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck