Penguins Unbound
Penguins Unbound > Past Meetings > 20110730 - Bash Programming > Shell Scripting (or old *nix tools) > 02 - Program Baics

02 - Program Baics

Page last modified 01:28, 30 Jul 2011 by goeko
    Table of contents
    1. 1. Command Line Script
    2. 2. Script File


    Command Line Script

    Writing shell script is a easy at

    for f in 1 2 3; do echo $f done

    that is a basic shell script. This script is a interactive script, or one that isn't in a file. I use A LOT of these script because the can get one thing done pretty quickly, and it isn't a task that I will need to do again, so no need to keep it around, or spend to much time on it.


    Script File

    You can also put all commands into a file and create a script.


    The first line of the script needs to be


    This tells the sytem that htis is a shell script, and that it should execute the command "/usr/bin/bash" to execute the script. (you can also use this to create scripts in other languages)


    In a shell script a # signals the start of a comment, it can start anwhere in the line and the rest of the line will be ignored.

    # A comment is just like this


    To get options in to script you can use the variables


    to get the number of options passed and

    $1 $2 $3 ... $x


    When you exit a shell script you should use "exit" with a number to pass back the value to the calling program.

    exit 0


    Once you have your script file you need to make the script excutable by seting the execute bit with the chmod commands

    chmod +x


    Here is a simple example.

    # Name: 
    # Description: An example script that does nothing.
    # Copyright Brian Dolan-Goecke 2011
    # Contact Brian Dolan-Goecke @
    # Global Variables
    # Not needed for this script.
    ## Make sure we are root
    #if test ${EUID} -ne 0 ; then
    #  echo "Not running as root, unable to make changes."
    #  echo "no point then! dieing..."
    #  # Exit now with error
    #  exit 2
    function usage() {
      NAME=`basename ${0}`
      echo "${NAME} options for script"
      echo "explain the options here"
    if test $# -le 0
      echo "No options, exiting..."
      exit 2
    echo "The number of options you passed was $#"
    echo "They were"
    while test $# -ge 1
      echo $1
    # Alls well that ends well.
    exit ${EXIT_STATUS}




    You should put a copy right and license on your scripts. (see )

    I try and number each "exit" uniquely, I usually increment them as a add them in the program so I can find out where it exited from the script.

    Powered by MindTouch Core