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
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..."
  select opt in "${options[@]}" "Skip DB Import"
    case $opt in
      *.mysql | *.sql.gz | *.sql)
        echo "Importing $opt ..."
        fin db import $opt
      "Skip DB Import")
        echo "Skipping DB Import..."
        echo "Invalid choice, please enter the number of your choice above."

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.

Sebastien Taggart
Technical Program Manager

The key to everything is mastery of your frame of mind. Everything is relative.

comments powered by Disqus