Basic information for shell script

1 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
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

function

usage ()
{
    echo "usage"
}

usage

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]

Tags: ,

Categories:

Updated:

Leave a comment