Tuesday 27 August 2013

shell scripts examples

Shell Script Examples

Example Shell Script: ls convenience1/8
One use for shell scripts is to provide a more convenient way of executing a complex pipeline or even just a single command with a complicated set of switches.
User often give these scripts very short names to save typing.
Here is one named l (that's the lower-case letter "ell") runs the ls command with a set of commonly used options.

ls -las "$@"

Example Shell Script: Arguments2/8
A simple shell script which prints details of its arguments.

echo My name is $0
echo My process number is $$
echo I have $# arguments
echo My arguments separately are $*
echo My arguments together are "$@"
echo My 5th argument is "'$5'"

% cd /home/cs2041/public_html/lec/shell/examples
% ./args.sh abc 1248 42 forty-two 'forty two'
My name is ./args.sh
My process number is 27876
I have 5 arguments
My arguments separately are abc 1248 42 forty-two forty two
My arguments together are abc 1248 42 forty-two forty two
My 5th argument is 'forty two'

Example Shell Script: Word Frequency3/8
Count the number of time each different word occurs in the files given as arguments.

sed 's/ /\n/g' "$@"|      # convert to one word per line
tr A-Z a-z|               # map uppercase to lower case
sed "s/[^a-z']//g"|       # remove all characters except a-z and '  
egrep -v '^$'|             # remove empty lines
sort|                     # place words in alphabetical order
uniq -c|                  # use uniq to count how many times each word occurs
sort -n                   # order words in frequency of occurrance
For example

% cd /home/cs2041/public_html/lec/shell/examples
% ./word_frequency.sh dracula.txt|tail
   2124 it
   2440 that
   2486 in
   2549 he
   2911 a
   3600 of
   4448 to
   4740 i
   5833 and
   7843 the

Example Shell Script: Counting4/8
A utility script to print the sub-range of integers specified by its arguments.
Useful to use on the command line or from other scripts

if test $# = 1
then
    start=1
    finish=$1
elif test $# = 2
then
    start=$1
    finish=$2
else
    echo "Usage: $0 <start> <finish>" 1>&2
    exit 1
fi

for argument in "$@"
do
    if echo "$argument"|egrep -v '^-?[0-9]+$' >/dev/null
    then
        echo "$0: argument '$argument' is not an integer" 1>&2
        exit 1
    fi
done

number=$start
while test $number -le $finish
do
    echo $number
    number=`expr $number + 1`    # or number=$(($number + 1))
done

Example Shell Script: Finding5/8
Search $PATH for the specified programs

if test $# = 0
then
    echo "Usage $0: <program>" 1>&2
    exit 1
fi

for program in "$@"
do
    program_found=''
    for directory in `echo "$PATH" | tr ':' ' '`
    do
        f="$directory/$program"
        if test -x "$f"
        then
            ls -ld "$f"
            program_found=1
        fi
    done
    if test -z $program_found
    then
        echo "$program not found"
    fi
done
Alternative implementation using while, and a cute use of grep and ||

if test $# = 0
then
    echo "Usage $0: <program>" 1>&2
    exit 1
fi

for program in "$@"
do
    echo "$PATH"|
    tr ':' '\n'|
    while read directory
    do
        f="$directory/$program"
        if test -x "$f"
        then
            ls -ld "$f"
        fi
    done|
    egrep '.' || echo "$program not found"
done
And another implementation using while, and a cute use of grep and ||

if test $# = 0
then
    echo "Usage $0: <program>" 1>&2
    exit 1
fi
for program in "$@"
do
    n_path_components=`echo $PATH|tr -d -c :|wc -c`
    index=1
    while test $index -le $n_path_components
    do
        directory=`echo "$PATH"|cut -d: -f$index`
        f="$directory/$program"
        if test -x "$f"
        then
            ls -ld "$f"
            program_found=1
        fi
        index=`expr $index + 1`
    done
    test -n $program_found || echo "$program not found"
done

Example Shell Script: Convert Filenames to Lowercase6/8
A script to convert the specified filenames to lower case.

if test $# = 0
then
    echo "Usage $0: <files>" 1>&2
    exit 1
fi

for filename in "$@"
do
    new_filename=`echo "$filename" | tr A-Z a-z`
    test "$filename" = "$new_filename" && continue
    if test -r "$new_filename"
    then
        echo "$0: $new_filename exists" 1>&2
    elif test -e "$filename"
    then
        mv "$filename" "$new_filename"
    else
        echo "$0: $filename not found" 1>&2
    fi
done

Example Shell Script: Watch a Website7/8
A script to repeated download a webpage until it matches a regex then notify an e-mail address.
For example to get e-mail when Kesha tickets (not for yourself of course) go on sale you might run:

% watch_website.sh http://ticketek.com.au/ 'Ke[sS$]+ha' andrewt@cse.unsw.edu.au

repeat_seconds=300  #check every 5 minutes

if test $# = 3
then
    url=$1
    regexp=$2
    email_address=$3
else
    echo "Usage: $0 <url> <regex>" 1>&2
    exit 1
fi

while true
do
    if wget -O- -q "$url"|egrep "$regexp" >/dev/null
    then
        echo "Generated by $0" | mail -s "$url now matches $regexp" $email_address
        exit 0
    fi
    sleep $repeat_seconds
done

Example Shell Script: convert GIF files to PNG8/8
This scripts converts GIF files to PNG files via the intermediate PPM format.

if [ $# -eq 0 ]
then
    echo "Usage: $0 files..." 1>&2
    exit 1
fi

if ! type giftopnm 2>/dev/null
then
    echo "$0: conversion tool giftopnm not found " 1>&2
    exit 1
fi

# missing "in ..." defaults to in "$@"
for f
do
    case "$f" in
    *.gif)
        # OK, do nothing
        ;;
    *)
        echo "gif2png: skipping $f, not GIF"
        continue
        ;;
    esac

    dir=`dirname "$f"`
    base=`basename "$f" .gif`
    result="$dir/$base.png"

    giftopnm "$f" | pnmtopng > $result && echo "wrote $result"
done

No comments:

Post a Comment