Simple Shell Scripts


Bash Shell Scripts

We have already created a file with linux commands and then made that file executable. For example, if we put the following commands into a file, then made that file executable, we would have a nifty new command to show us who was logged into our machine:
     date
     who
That file containing the linux commands is an example of a very simple shell script.

Shell scripts that do more complicated operations require a more complicated syntax. There are multiple shell languages. Each language has its own syntax for if statements, how assignments works, using variables, etc. We will use the bash shell.

All bash shell scripts must have the following on the first line of the file:
    #!/bin/bash

Note that in bash shells, after the first line, all lines that begin with # are comments. Hence, the following shell does nothing.
    #!/bin/bash
    # Steve Dannelly
    # Lab 14
You will need to put your name on all your lab assignments.


echo

Echo is a very common and useful command. Here is an example of a script with a few echo commands
    #!/bin/bash
    # echo examples
    
    echo "This is an example of using echo."
    echo -n "The current directory is "
    echo $PWD

The first echo command just prints the contents of the string inside the quotes.

The second echo also prints a string but does not add a return character. Note the second string ends in a space just so the output looks pretty.

The third echo prints the contents of a built-in variable that the system uses to keep track of your current directory (PWD is short for Print Working Directory).

Running the above script files would create the following output:
    This is an example of using echo.
    The current directory is /home/ACC.dannellys2/csci208lab


Variables

See pages 296-302 for more information about variables.

A few variables are already built into the system. To see the names and values of system variables, type "set" on the command line.

To create a new variable, just start using it. No need to declare it.

Your variable names must begin with a letter or the underscore character ( _ ).

The bash format for variable assignment is
    var=contents
DO NOT put spaces around the = symbol.

This shell script
    #!/bin/bash
    # echo examples
    
    name1=bob
    name2=name1
    name3=$name1
    
    echo $name1
    echo $name2
    echo $name3
would create the following output
    bob
    name1
    bob

The first assignment puts the string bob inside a new variable named name1.

The second assignment creates a new variable named name2 and puts inside it the string name1.

The third assignment creates a new variable named name3 and puts inside it the contents of the variable named name1.

Each of the echo commands prints the contents of a different variable.


Command Line Arguments

Arguments to your shell script are placed into numbered variables. $1 is the first command line argument. $2 is the second. etc...

$# is the number of arguments.

For example, shell3 is simple shell that I wrote to demonstrate how to use command line arguments.

> cat shell3
#!/bin/bash
# demo of arguments

echo "There are " $# " arguments."
echo "The first argument is " $1
echo "The name of this script is " $0


> shell3 hi mom
There are  2  arguments.
The first argument is  hi
The name of this script is  ./shell3


If Statements

See Chapter 27 for more information about conditionals and control statements.

The format for if statement is
     if [ condition ]
          then
               true stuff
          else
               false stuff
     fi
The "fi" is "if" backwards, and ends an if block.

The following example uses an if to make sure the user input an argument. If the user input no arguments, the script prints a message then exits. If the user input some arguments, then the script prints how many.

So long as the script did not exit due to too few arguments, the scripts runs a command to count the number of lines in the filename provided. Note, the single quotes are not the normal single quotes. These weird quotes cause the output of the command, not the contents of the string, to go into the variable named lines.

#!/bin/bash
# an if statement

# check for enough arguments
if [ $# = 0 ]
   then
      echo "No Arguments"
      exit 1
   else
      echo $# " Arguments"
fi

# count the number of lines
lines=`cat $1 | wc -l`

# output the results
echo -n "The file named "
echo -n $1
echo -n " contains "
echo -n $lines
echo " lines."
That script would produce this output:
> shell4
No Arguments

> shell4 shell4
1  Arguments
The file named shell4 contains 21 lines.


More Complex If Statements

Supposed you want to write something like a C++ case statement. Case statements are useful when there are several possible conditions for a variable, but you only want to do one action. The way to do that in a bash shell is to write a nested if statement.

Here is an example of a nested if statement. The elif is short for "else-if". Else-If statements are used in many languages, but not C++. The else must go last.

#!/bin/bash
# nested if statements

if [ $# -eq 0 ]
   then
      echo "Error: missing filename"
      exit 1
fi

if [ -r $1 ]
   then
      echo -n "First 5 lines of "
      echo $1
      head -n 5 $1
elif [ -f $1 ]
   then
      echo -n "The file "
      echo -n $1
      echo " exists but is not readable to the script."
else
      echo -n "The file "
      echo -n $1
      echo " does not exist."
fi

If you want to compare two strings, use ==.

If you want to compare two integers, use -eq, -ne, -lt, -gt, -ge, or -le
Those are short for equal, not equal, less than, greater than, greater then or equal, and less than or equal.

If you want to use compound logic, think again. If you still want to use compound logic you can do something like this:

    if [[ $num -eq 3 && $stringvar == "foo bar baz" ]]


Assignment Number 14

Way back in assignment number 9, you figured out how to count CSCI and CIFS graduates. Expand that to include ACCT, ENTR, MGMT, and MKTG graduates.

Also, the user should provide the name of the file to process. If the user does not provide a file name, then print a usage error and quit.

For example

> majors
Usage: majors filename

> majors lab9.txt
ACCT    23
CSCI    2
CIFS    1
ENTR    5
MGMT    20
MKTG    22
Be sure to test your script with input other than the file lab9.txt!!!!


Assignment Number 15

Now add another feature to the previous script. Allow the user the option to view names. The option should be "-names". If the user includes that option then print the names as well as the graduation counts.

For example

> majors2
Usage: majors2 [-names] filename

> majors2 lab7.txt
CSCI    2
CIFS    1
ACCT    23
ENTR    5
MGMT    20
MKTG    22

> majors2 -names lab7.txt
CSCI    2
Dickson, Anthony James            BS      CSCI   MATH
Downs, Christopher Paul           BS      CSCI   BADM
************************************************************
CIFS    1
Anderson, Ian                     BS      BADM          CIFS
************************************************************
ACCT    23
Alexander, Amy Elizabeth          BS      BADM          ACCT
                                                        ACCT
Ayers, Brittany Nicole            BS      BADM          ACCT
Brown, Lyeshea Semondre Shayron   BS      BADM          ACCT
Calloway, Logan Mackenzie         BS      BADM          ACCT
Childers, Jamie Leigh             BS      BADM          ACCT
Flick, Heather Wrenee             BS      BADM          ACCT
Foster, Rodney Tyrone             BS      BADM          ACCT
Gallman, Antonio James            BS      BADM          ACCT

 blah  blah  blah  blah