Tips for Writing Bash Script

2024-02-24 / Linux Development Bash

Bash (Bourne Again SHell) is a popular command-line shell and scripting language. It is commonly used on Unix-like operating systems, including Linux.

1. Writing functions

Bash functions are a way to group a set of commands and logic into a reusable block in a Bash script. They allow you to encapsulate common tasks or complex sequences of commands into a single callable entity. Here’s an example of how to define and use a Bash function:

function hello() {
  ...
}

or

hello() {
  ...
}

Note: bash function will only return the return code of the last command that run in function.

For example: the hello function will not catch the return code of command1

hello() {
  command1
  command2
}

If you care about the execution results of all instructions throughout the entire function process, you need to use the “&&” symbol to chain all the commands together. Such as:

hello() {
  command1 && \
  command2
}

2. set -e

set -e is a common command used in Bash scripts. It sets an error handling flag that causes the script to exit immediately if any command within the script fails.

#!/bin/bash

set -e

# Some commands here...

command1
command2
#...

# If any command fails, the script will exit here

3. realpath

realpath is a command in bash that is used to get the absolute path of a file or directory.

4. dirname

dirname is a built-in command in Bash scripts that returns the directory name part of a given path or the directory path of a given file path.

5. BASH_SOURCE

BASH_SOURCE is an internal variable in the Bash shell. It holds the path of the script or function that is currently being executed.

You can get absolute path of the bash script file you are running.

#!/usr/bin/env bash

set -e

bash_script="$(realpath "${BASH_SOURCE[0]}")"

And set the dirctory where bash script in as working directory.

#!/usr/bin/env bash

set -e

workdir="$(realpath "$(dirname "$(realpath "${BASH_SOURCE[0]}")")")"
cd "${workdir}"

6. confirm via read

In Bash, you can use the read command to prompt for confirm input from the user. Here’s an example of how to write a confirm input in Bash:

read -p "Are you sure [y/n]? " -r name
if [[ ! $name =~ ^[Yy]$ ]]
then
  echo "==> Aborted"
  exit 0
fi

7. variable requirement

The naive way to check if a variable is empty.

if [ "${variable}" == "" ]; then
  ...
fi

The tidy code could be like:

a="${variable:?}"