How to write Bash Script for beginner


Bash script is really powerful and easy to write. But we need to take care security and maintenasability.
This articles shows how to write Bash script for beginner.

😼 Script Template

First, I show basic template for shell script:

#!/bin/bash
#
# Script description
#
# This script is ...
#

# Configuration for this script
# -e: Stop this script if an error happened
# -u: Stop script if there was an undefined variable
# -C: Prevent overwrite an existing file
set -euC

# Global constant
readonly WORK_DIR=/tmp/mydir

# Global variable
VAL_A=0

# Parsing an argument
function usage {
cat <&2
Usage: $0 [-a val] [-b]
item item
-a val Option 1
-b Option 2
-c Option 3
EOS
exit 1
}

while getopts "a:bc" OPT; do
case $OPT in
a) VAL_A=$OPTARG ;;
b) FLAG_B=1 ;;
c) FLAG_C=1 ;;
\?) usage;;
esac
done

shift $((OPTIND - 1))

GLOBAL_VAL=$1

if [[ "$GLOBAL_VAL" == "" ]]; then
usage
fi

# Function definition
function main {
# do something
}

# Entry point
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$VAL_A" "$@"
fi

👽 Important Point

  • When expanding variables, be sure to enclose with "
  • Write comments when creating commands and functions
  • Use $ (cmd) to get the standard output of the command result as a variable
  • Define variables with local or readonly
  • Use trap if you want to always process at the end of the script

😎 Appendix

Stop when occuring error

If error was happened in your Bash script, you should stop the process.
So, you should set set -e -u in top of your Bash script.

#!/bin/sh
set -e -u # Stop when occuring error
cd "${0%/*}/../"

Get the size of a directory by CLI

du -ah ./public/

How to handle error

#!/bin/bash

function my_command() {
# do something
return 1
}

my_command()
if [ $? -gt 0 ]; then
# handle error
fi

Get timestamp

NOW=$(date "+%Y.%m.%d-%H.%M.%S")

How to find your IP address

curl ifconfig.me

🎳 References

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!