Bash Scripting Notes

This is my notebook for bash scripting.

Styling

Use Google style guide for shell.

Organization

Use functions; use a main function and call it by main "$@" at the end of the script.

Boolean variable

Use 1 or 0 literal for boolean; test by [[${bool_val} -eq 1 ]].

Local variable

Use local for function local variable; seprate declaration and assignment.

String operation

See this manual.

getopt

Always quote "$@" to preserve correct word splitting.

Read password

Use read -p <prompt> -s <variable>; echo to read password.

Use sudo

Include this function and call it before you’re going to use sudo.

1
2
3
prepare_sudo() {
sudo -v
}

Here document

Use Here document for usage(), etc.

You can utilize the following technique to write a here document as root

1
sudo tee "${profile_path}" >/dev/null <<EOF

Script name

``
name=$(basename “$0”)

1
2

## Report error

error() {
echo “${FUNCNAME[1]}: $@” >&2
}

1
2
3
4
5
6
7

## Configuration file

You can source an external configuration file as bash script. A bit unsafe though.

```bash
source example.conf

Wait for certain condition

1
2
3
4
for i in $(seq 0 "${timeout}"); do
check_something;
sleep 1;
done

Watch file changes

Use inotifywait.

Colored makepkg-like functions

1
2
3
4
5
6
7
8
9
10
11
12
msg_blue()·{
printf·"${BLUE}==>${ALL_OFF}${BOLD}·$1${ALL_OFF}\n"
}

note()·{
printf·"${BLUE}==>${ALL_OFF}${YELLOW}·NOTE:${ALL_OFF}${BOLD}·$1${ALL_OFF}\n"
}

ALL_OFF="$(tput·sgr0)"
BOLD="$(tput·bold)"
BLUE="${BOLD}$(tput·setaf·4)"
YELLOW="${BOLD}$(tput·setaf·3)"