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:

# 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

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

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

shift $((OPTIND - 1))


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

# Function definition
function main {
# do something

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

😼 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.

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

Get the size of a directory by CLI

du -ah ./public/

How to handle error


function my_command() {
# do something
return 1

if [ $? -gt 0 ]; then
# handle error

Get timestamp

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

🐠 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!!