FLOPPIX Home | FAQ | Download | Labs | ToC | Back |  Next 

Very Simple Bash Scripts


  1. A bash script is a file containing a list of commands to be executed by the bash shell.

  2. The very simplest scripts contain a set of commands that you would normally enter from the keyboard. For example: the following lines are stored in the scripts colorme.
    #! /bin/bash
    # script to turn the screen blue
    setterm -background blue
    echo It is a blue day
    Line 1: specifies which shell should be used to interpret the commands in the script.
    Line 2: is a comment (has no effect when the script is executed).
    Line 3: sets the background colour.
    Line 4: displays a message.

  3. To run the script:

  4. Using variables in a script
    Variables are created when you assign a value to them ( eg: COLOR=blue )
    To use the variable, put a $ before the variable name. ( eg: echo $COLOR )
    Modify the colorme script to use the color variable as follows:

    #! /bin/bash
    setterm -background $COLOR
    echo It is a $COLOR day
  5. Getting user input
    A script can get input from the user while it is running. Use the echo command to display a prompt on the screen and the read command to get the input.
    #! /bin/bash
    echo -n "Pick a screen color (blue, yellow, red ): "
    read -e COLOR
    setterm -background $COLOR
    echo It is a $COLOR day
  6. Passing Parameters on the command line:
    You can also pass parameters to the script on the command line. Bash will accept up to 9 parameters separated by spaces. The first parameter is $1, the second parameter is $2, etc. The colorme script using input parameters is shown below.
    #! /bin/bash
    setterm -background $1
    echo It is a $1 day
    To run the script, use the command: colorme red
    In this case, $1 will be given the value "red".
    Run the script again using the command: colorme blue
    This time, $1 will have the value "blue".


  1. Write a script called checking that displays information about a specified user.
    The script should:

    Test your script using your own username. Then, login on another console as floopy, switch back to your own console and make sure that your script displays the correct data about floopy.

  2. Code a script called dirchk that displays data about the current directory. The script should:

    To test your script, you should create some subdirectories, some files that are zero length using touch and some files that are not zero length using vi, redirection or cp.

Copyright © L.M.MacEwan
FLOPPIX Home | FAQ | Download | Labs | ToC | Back |  Next