Read a filtered list of files from a directory and ask the user to choose one (Bash)

One of the most powerful aspects of Docksal is how easy it is to extend base functionality with Bash scripts.  A common use-case is to automate importing databases when initializing projects.  The snippet below reads all DB files from a directory and presents the user with a choice about which file to import:

# Get a list of *.mysql | *.sql.gz | *.sql in /db/ and let user choose which to import
unset options i
while IFS= read -r -d $'\0' f; do
  options[i++]="$f"
done < <(find ${PROJECT_ROOT}/db/ -maxdepth 1 -type f \( -name "*.mysql" -o -name "*.sql.gz" -o -name "*.sql" \) -print0 )

echo "Press [Enter] to choose DB to import"
read -t5 -p "(times out in 5 seconds) "
if [ $? -gt 0 ]; then
  echo ""
  echo "Timed out waiting for response.  Skipping DB import..."
else
  select opt in "${options[@]}" "Skip DB Import"
  do
    case $opt in
      *.mysql | *.sql.gz | *.sql)
        echo "Importing $opt ..."
        fin db import $opt
        break
        ;;
      "Skip DB Import")
        echo "Skipping DB Import..."
        break
        ;;
      *)
        echo "Invalid choice, please enter the number of your choice above."
        ;;
    esac
  done
fi

This searches a directory for files matching the extensions listed, then asks the user to choose from.  I added a timeout because this snippet is meant to be run as part of a larger script that runs unattended.  

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.