Skip to content

Multi-UI Bash Script

This blog post aims to show the structure of a multimode UI bash script.

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:

main.sh
#!/bin/bash
# ...
# get the directory where the script itself is stored
script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# source files using the absolute path
source "$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:

ui_text.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 "$*"
}
# ...

Then, use a --mode flag to select which UI file to source:

main.sh
#!/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 stored
script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# source files using the absolute path
source "$script_dir/common/change_permission_logic.sh"
# append $MODE variable into 'source' call
source "$script_dir/common/ui_${MODE}.sh"

In this way:

  • if $MODE is set to text, then ui_text.sh file will be sourced,
  • if $MODE is set to tui, then ui_tui.sh file will be sourced.

Call the script:

Terminal window
./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.