Bash
Bash:如果未提供參數,則顯示提示
同時支持腳本提示和參數的最佳方式是什麼?如果未提供參數,我想顯示提示。
有沒有比這更好/更短的東西?⇩
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
您可以使用函式將其縮短一點:
#!/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"
雖然這需要
bash
並且不會在sh
.
您可以使用參數擴展來做到這一點
${variable:-default}
例如:
function get_value_as_arg_or_prompt() { value=${1:-$(read -p "Enter: " x && echo "$x")} echo "$value" }
如果給出一個論點:
$ get_value_as_arg_or_prompt "Hi there" Hi there
如果不給出論點:
$ get_value_as_arg_or_prompt Enter: I'm here I'm here