Other Shell Features

What other things can enhance my scripts


Sometimes you want a script to run as a daemon, in the background and never ending. To do this properly you need to be able to detach your script from its controlling TTY—that is, from the terminal session used to start the daemon.

Reusing codes with includes and sourcing

    # vars.sh 

    source vars.sh
    printf "My name is %s\n" $name
    printf "My age is %s\n" $age
    printf "My color is %s\n" $color

Defining Functions

Function example

    function usage ()
        printf "usage: %s [ -a | - b ] file1 ... filen\n " $( basename $0 )

    if [ $# -lt 1 ]

Sending values to functions

    function add ()
       z=$(( $1 + $2 ))
       printf "z is %s" $z

    add 8 12 

Returning values from a function

Returning values from a function

Other function stuff


    function sample ()
            echo "We are in $FUNCNAME"


Redefining commands with alias

Counting elapsed time


    sleep 4
    echo "Run-time = $(($SECONDS - $started)) seconds..."

    bash seconds
    time bash seconds


Real is wall clock time - time from start to finish of the call. This is all elapsed time including time slices used by other processes and time the process spends blocked (for example if it is waiting for I/O to complete).

User is the amount of CPU time spent in user-mode code (outside the kernel) within the process. This is only actual CPU time used in executing the process. Other processes and time the process spends blocked do not count towards this figure.

Sys is the amount of CPU time spent in the kernel within the process. This means executing CPU time spent in system calls within the kernel, as opposed to library code, which is still running in user-space. Like ‘user’, this is only CPU time used by the process.