Unix: Writing more maintainable shell scripts

By  

myFunctions (assuming you call your functions file myFunctions.

#!/bin/bash

function ask () {
    echo -n "$question> "
    read ans
    case $ans in
        [Yy]*) ans="Y";;
        [Nn]*) ans="N";;
        *)     ans="-";;
    esac
}

Try it like this:

#!/bin/bash

. myFunctions

question="Continue?"; ask
if [ $ans != "Y" ]; then
    echo "OK, have a nice day"
    exit
fi

You can add as many functions as you like to your function "libraries" or group your functions in a series of files that represent the various types of data processing you perform.

#!/bin/bash

function ask () {
    echo -n "$question> "
    read ans
    case $ans in
        [Yy]*) ans="Y";;
        [Nn]*) ans="N";;
        *)     ans="-";;
    esac
}

function lower()
{
    local str="$@"
    local output
    output=$(tr '[A-Z]' '[a-z]'<<<"${str}")
    echo $output
}

function is-root {
    if [ "$UID" -ne 0 ]
        then echo "Please run as root"
        exit 1
    fi
}

function greet {
    echo Hello, $USER
}

Give your scripts understandable names and they'll be easier to find and easier to use. I often start my scripts by calling them "tryme" until they've been proven to work pretty well. Then I give them meaningful names like "findProblems" or "genStats" -- something that reminds me of what they're intended to do for me.

Also use meaningful names for your variables. $loopcounter is probably better than $lc and the longer names really aren't much of a hardship since you won't be typing them again and again.

Use comments, but don't get carried away. If you put in too many comments, probably no one will read them. Only comment major things that are happening in your scripts or commands that are complex.

Put your scripts in a reasonable location -- /usr/local/bin or your own bin directory -- and maybe tar them up from time to time so you have a handy backup. I actually prepare documents describing some of the more complex things that I do with scripts. If I start with a huge log file, summarize it in some meaningful way and then pass the results through another script that prepares a report, I want to remember the entire flow -- where the scripts run, how output is exchanged -- especially if multiple systems are involved in the overall process.

Photo Credit: 

flickr / iriskh

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question