bash code snippets

This is going to be a collection of bash code snippets:

  1. Check if the user running the script is root:
    # make sure we're running as root
    if [ `id -u` != 0 ]; then { echo "Sorry, must be root.  Exiting..."; exit; } fi
  2. Check the successful execution of previous command:
    if (( $? )); then
            {
                    echo "could not executed successfully";
                    exit;
            }
    fi;
  3. Check number of arguments:
    # Check for proper number of command line args.

    EXPECTED_ARGS=1
    E_BADARGS=65

    if [ $# -ne $EXPECTED_ARGS ]
    then
      echo "Usage: `basename $0` {arg}"
      exit $E_BADARGS
    fi
  4. Array loops:
    VALUES=("value1" "value2" "value3" "..." "valueN")

    for ((i=0; i<${#VALUES[@]}; i++))
    do
      echo ${VALUES[$i]}
    done

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
quoted here document

cat <<\EOF
The answer is '$foo'!
EOF

The backslash before the EOF makes the here document a literal one.

Capture PIDs at execution

"$!" will return pid of last background process.
"$$" will return current process pid.

To kill all processes started by the main script:

pkill -g <PID>

script location

SCRIPT_NAME=`basename $0`
SCRIPT_PATH=$(/usr/sbin/lsof -p $$ | grep $SCRIPT_NAME | awk '{print $9}')
SCRIPT_DIR_PATH=`dirname $SCRIPT_PATH`
echo "Name of script: $SCRIPT_NAME"
echo "Path to script: $SCRIPT_PATH"
echo "Path to script directory: $SCRIPT_DIR_PATH"
echo "Script containing directory: ${SCRIPT_DIR_PATH##*/}"

pid check

PID_FILE=/var/run/`basename $0`.pid

# Check if the PID is running
if [ -f "$PID_FILE" ]
    &nbsp;   then
    &nbsp;    &nbsp;    &nbsp; MYPID=`head -n 1 "$PID_FILE"`
    &nbsp;    &nbsp;    &nbsp; TEST_RUNNING=`ps -p ${MYPID} | grep ${MYPID}`

    &nbsp;   if [ -z "${TEST_RUNNING}" ]
    &nbsp;    &nbsp;    &nbsp; then
    &nbsp;    &nbsp;    &nbsp;    &nbsp;    echo "PID file exists but PID [$MYPID] is not running... creating new PID file [$PID_FILE]"
    &nbsp;    &nbsp;    &nbsp;    &nbsp;    echo $$ > "$PID_FILE"
    &nbsp;   else
    &nbsp;    &nbsp;    &nbsp; echo "`basename $0` is already running [${MYPID}]... quitting"
    &nbsp;    &nbsp;    &nbsp; exit -1
fi
else
    &nbsp;   echo "`basename $0` not running... creating new PID file [$PID_FILE]"
    &nbsp;   echo $$ >> "$PID_FILE"
fi

merge files

Merge corresponding lines of one or more files into vertical columns, separated by tab.

$ paste merge1.txt merge2.txt > output.txt

pre-catenate file

$ echo "Title goes here" | cat - test.txt > test.txt.new

or with here:

$ cat - test.txt <<<"Title goes here" > test.txt.new

Default args value if empty

DEFAULT=${1:-<value>}

Month End Date

$ date +%Y%m%d -d "2008-01-15 +1 month -15 days"

Comment