Basic information for shell script

2 minute read

A shell script is a computer program designed to be run by the Unix shell, a command-line interpreter. The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manipulation, program execution, and printing text. A script which sets up the environment, runs the program, and does any necessary cleanup, logging, etc. is called a wrapper.

Link : Shell script wiki

Check parameters

USAGE=`basename $0`" [param1] [param2]"
if [ $# = 0]
then
    echo $USAGE
    exit
else
    echo "Starting..."
fi

if [ $# -gt 1 ]
then
    # ...
fi

if [ $# -gt 2 -a $3 -ne 0 ]
then
    # ...
fi

if [ $# -gt 3 -a $4 != "TEST" ]
then
    # ...
fi

if, for, while

# if statement
if [ "$SVRNM" != "svrnm" ] ; then
  echo $SVRNM
elif [ "$SVRNM" != "svrid" ] ; then
  echo $SVRNM
fi

# for statement
MLIST="AA BB CC DD EE FF"
for ITEM in $MLIST
do
    if [ "$ITEM" = "CC"] ; then
        break
    fi
    # ....
done

# while statement
IDX=10
while [ 1 ]
do
    if [ $IDX = 0 ]
    then
        break
    fi
    sleep 1
    IDX=`expr $IDX - 1`
    echo "$IDX"
done

Date format

CTIME=`date '+%Y%m%d.%H%M%S'`
echo $CDATE

echo `date '+%Y-%m-%d %H:%M:%S' -d'10 second ago'`
echo `date '+%Y-%m-%d %H:%M:%S' -d'30 minute ago'`
echo `date '+%Y-%m-%d %H:%M:%S' -d'3 hour ago'`
echo `date '+%Y-%m-%d %H:%M:%S' -d'2 day ago'`
echo `date '+%Y-%m-%d %H:%M:%S' -d'1 week ago'`
echo `date '+%Y-%m-%d %H:%M:%S' -d'1 month ago'`
echo `date '+%Y-%m-%d %H:%M:%S' -d'3 year ago'`
echo `date '+%Y-%m-%d %H:%M:%S' -d'3 year 7 month ago'`

Future : without ago

echo `date '+%Y-%m-%d %H:%M:%S' -d'this friday'`
echo `date '+%Y-%m-%d %H:%M:%S' -d'last monday'`
echo `date '+%Y-%m-%d %H:%M:%S' -d'next monday'`

function

usage ()
{
    echo "usage"
}

usage

# Print function example
LOGDT=`date '+%Y%m%d'`
ZLOG=$HOME/test.log.$LOGDT

print_func() {
    CTIME=`date '+%Y-%m-%d %H:%M:%S'`
    echo "$CTIME $1" >> $ZLOG
}

print_func "Hello world"

Etc

# Retrieve all files starting [filename_] and ending with 3 characters.
set -x

set +x

# Retrieve all files starting [filename_].
ls -al filename_*

# Print the command
set -x
echo "Print this command with set -x/+x"
set +x

# Formatting
echo "ABCDEF ABCDEF B CCC DDDDDD" | awk '{printf("[%-3.3s][%-3s][%5s][%-10s][%10s]\n", $1, $2, $3, $4, $5)}'

# Result: [ABC][ABCDEF][    B][CCC       ][    DDDDDD]

Check if it start with something

HOSTNAME=`hostname`
if [[ "$HOSTNAME" == dv* ]] || [[ "$HOSTNAME" == ts* ]] ; then
    echo "It starts with dv or ts"
else
    echo "Not defined"
fi

Tags: ,

Categories:

Updated:

Leave a comment