User Tools

Site Tools


buildsw:reference:bash

Bash Reference

Topics

Tutorials

Bash Prompt and Environment

Bash Testing

Bash Here Docs

Running as another user

Bash type conversion

Bash Static Analysis (linting)

Shebang line

#!/bin/bash

Or for better portability:

#!/usr/bin/env bash

Starting a script in the directory where it resides

cd "$(dirname "$0")"

Setting a variable to the current directory

run_dir=`pwd`

Usage example

usage () {
  echo ""
  echo "Usage:"
  echo ""
  echo "  $0 cmd arg [option]"
  echo ""
}

usage
exit 1

Checking the number of arguments

if [ "$#" -ne 1 ]; then
  usage
  exit 1
fi

Checking the return code

if [ $? -eq 0 ]; then
  echo "INFO: command ran successfully"
  exit 0
else
  echo "ERROR: command failed" >&2
  exit 1
fi

Debugging Flags

set -x    # activate debugging
set +x    # deactivate debugging

If Statements

Case Statement

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  status)
    status
    ;;
  restart)
    stop
    start
    ;;
  *)
    usage
    exit 1
esac

Looping

# declare an array called array and define 3 values
array=( one two three )
for i in "${array[@]}"
do
  echo $i
done

Timestamps

# timestamp
ts_now=$(date +%Y%m%d_%H%M%S_%Z)

Logging

echo "ERROR:   " | tee -a $log_filename
echo "WARNING: " | tee -a $log_filename
echo "INFO:    " | tee -a $log_filename
echo "DEBUG:   " | tee -a $log_filename

Logging an error_count

error_count=0
log_filename="logfile.txt"

# run some commands
run_cmd_a
cmd_retval_a=$?
error_count=$(( $error_count + $cmd_retval_a ))

run_cmd_b
cmd_retval_b=$?
error_count=$(( $error_count + $cmd_retval_b ))

if [ $error_count -eq 0 ]; then
  echo "INFO: error_count: ${error_count}" | tee -a $log_filename
  exit 0
else
  echo "ERROR: error_count: ${error_count}" | tee -a $log_filename
  exit 1
fi

String Substitution

var2=$(echo "$var1"  | sed 's/from/to/g')

String Trim

# trim leading and trailing whitespace
trim_ws () {
  in_string=$1
  out_string="$(echo -e "${in_string}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
  echo "$out_string"
}

Calling the function:

src_location=$(trim_ws "$src_location_ws")

String Length

length_of_var=${#var}

Checking for file existence

if [ -f "$filename" ]; then
  echo "$filename exists"
fi

dirname and basename

$ var1="/home/user/project/example.txt"

$ dir1=$(dirname "${var1}")

$ echo "${dir}"
/home/user/project

$ basename "${var1}"
example.txt

Functions

Exit Codes

buildsw/reference/bash.txt · Last modified: 2017/03/24 15:41 by gwhiteman