brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: select gives a bash script a numbered menu in a few lines

Bash
~/tips/tip-bash-select-menu

select action in start stop status quit; do

Let a user pick an option by number without writing your own menu loop.

For a small helper script that asks what to do, writing the menu, the number check and the loop by hand is boring. Bash has a builtin that does all of it.

select prints the list with numbers, reads a choice and puts the chosen word in your variable:

PS3='Pick an action: '
select action in start stop status quit; do
  case $action in
    start|stop|status) systemctl "$action" nginx ;;
    quit) break ;;
    *) echo "invalid choice: $REPLY" ;;
  esac
done

It shows 1) start, 2) stop and so on, then the prompt from PS3. After the user types 2, $action holds stop and $REPLY holds the raw input, which helps in that error message.

It keeps asking until something calls break, so always give the user a way out. Ctrl-D on the prompt also ends it.

The menu goes to stderr, not stdout, so redirecting the script’s output to a file does not hide it. I think it fits small admin helpers well; for anything with more than one choice at a time, or when the script must also run unattended, plain arguments with getopts are the better choice.

Further reading: Bash manual: Conditional Constructs (select)

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link