Published at
Updated at
Reading time
This post is part of my Today I learned series in which I share all my web development learnings.

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;;

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! ๐ŸŽ‰

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 4 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles