Multi-UI Bash Script
Introduction
Section titled “Introduction”This blog post aims to show the structure of a multimode UI bash script.
The structure
Section titled “The structure”The structure is:
Directoryscripts/
- main.sh starting point of the script
Directorycommon/
- logic.sh business logic functions
- ui_text.sh text-based UI functions
- ui_tui.sh TUI-based UI functions
main.sh script can use the functions written within logic.sh, ui_text.sh and ui_tui.sh by using source keyboard:
#!/bin/bash
# ...
# get the directory where the script itself is storedscript_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# source files using the absolute pathsource "$script_dir/common/change_permission_logic.sh"Let’s write UI functions with the same name within both the UI scripts: ui_text.sh and ui_tui.sh:
#!/bin/bash
ui_prompt() { local message="$1" read -rp "$message: " REPLY echo "$REPLY"}
ui_error() { local msg="$1" echo "# ERROR: $msg"}
ui_info() { echo "$*"}
# ...#!/bin/bash
ui_prompt() { eval `resize` whiptail --inputbox "$1" $(( $LINES / 2 )) $(( $COLUMNS / 2 )) 3>&1 1>&2 2>&3}
ui_error() { local msg="$1"
eval `resize` whiptail --title "Error" --msgbox "$msg" $(( $LINES / 2 )) $(( $COLUMNS / 2 ))}
ui_info() { eval `resize` whiptail --msgbox "$*" $(( $LINES / 2 )) $(( $COLUMNS / 2 ))}
# ...Then, use a --mode flag to select which UI file to source:
#!/bin/bash
# default mode is "text"MODE="text"
parse_args() { # parse --mode flag while [[ "$#" -gt 0 ]]; do case "$1" in --mode=*) MODE="${1#*=}" ;; --mode) MODE="$2"; shift ;; *) echo "Unknown parameter: $1"; exit 1 ;; esac shift done}
parse_args "$@"
# get the directory where the script itself is storedscript_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# source files using the absolute pathsource "$script_dir/common/change_permission_logic.sh"
# append $MODE variable into 'source' callsource "$script_dir/common/ui_${MODE}.sh"In this way:
- if
$MODEis set totext, thenui_text.shfile will be sourced, - if
$MODEis set totui, thenui_tui.shfile will be sourced.
Call the script:
./main.sh # text mode by default
# or Terminal-based UI./main.sh --mode tui# also, can call it with '=' sign./main.sh --mode=tui--mode flag modify the value of $MODE variable seen above.
ui_text.sh and ui_tui.sh hold functions with the same name.
In this way, neither main.sh nor logic.sh will behave differently based on the chosen UI.