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 | prepare_sudo() { |
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 |
|
error() {
echo “${FUNCNAME[1]}: $@” >&2
}
1 |
|
Wait for certain condition
1 | for i in $(seq 0 "${timeout}"); do |
Watch file changes
Use inotifywait
.
Colored makepkg-like functions
1 | msg_blue()·{ |