Bash: show prompts if arguments weren’t provided

argumentsbashpromptscripting

What is the best way of supporting in the script prompts and arguments at the same time? I want to show prompts if arguments weren't provided.

Is there something better/shorter than this? ⇩

PROJECT_DIR=$1
SITE_NAME=$2
ADMIN_PWD=$3
THEME_DIR=$4
THEME_NAME=$5

if [ -z "${PROJECT_DIR}" ]; then
    echo "Directory where project resides:"
    read PROJECT_DIR
fi

if [ -z "${SITE_NAME}" ]; then
    echo "Name of the website:"
    read SITE_NAME
fi

if [ -z "${ADMIN_PWD}" ]; then
    echo "Admin password:"
    read ADMIN_PWD
fi

if [ -z "${THEME_DIR}" ]; then
    echo "Directory of the theme:"
    read THEME_DIR
fi

if [ -z "${THEME_NAME}" ]; then
    echo "Name of the theme:"
    read THEME_NAME
fi

Best Answer

You can shorten it a bit by using a function:

#!/bin/bash

ask()
{
  declare -g $1="$2"
  if [ -z "${!1}" ]; then
    echo "$3"
    read $1
  fi
}

ask PROJECT_DIR "$1" "Directory where project resides:"
ask SITE_NAME   "$2" "Name of the website:"
ask ADMIN_PWD   "$3" "Admin password:"
ask THEME_DIR   "$4" "Directory of the theme:"
ask THEME_NAME  "$5" "Name of the theme:"

echo "$PROJECT_DIR $SITE_NAME"

This requires bash though and won't work in sh.

Related Question