How to add interactive questions to bash scripts

1 min read

This post is part of my Today I learned series in which I share all my learnings regarding web development.

I was chatting to my colleague Jeff about dotfiles today and he showed me something really interesting. He uses some handy shell functions in his terminal to secure critical but repetitive git tasks.

pushToPreview() {
  CURRENTBRANCHNAME="$(git rev-parse --abbrev-ref HEAD)"
  echo "Working branch: $CURRENTBRANCHNAME"

  echo "Force push $CURRENTBRANCHNAME to preview?"
  select yn in "Yes" "No"; do
    case $yn in
      Yes ) echo "Updating preview from $CURRENTBRANCHNAME" && git push -f origin $CURRENTBRANCHNAME:preview; break;;
      No ) break;;
    esac
  done
}

I don't want to get too much into details what this snippet above does but it includes a yes/no prompt that stops the shell script and waits for user input?!

If the user enters 1 a git push -f is performed. 😲

Interactive prompt in bash

It turns out the select statement makes this possible. I digged a bit and found this clear definition of what select does.

- generates a menu of each item in list, formatted with numbers for each choice
- prompts the user for a number
- stores the selected choice in the variable name and the selected number in the built-in variable REPLY
- executes the statements in the body
- repeats the process forever (but see below for how to exit)

This is really nice because with select I can customize commands like a rm -rf or the mentioned git push -f easily and safe myself some future headaches without the need for an additional library or something similar! 🎉

Tags

Load time