# The == comparison operator behaves differently within a double-brackets# test than within single brackets.
[[ $a == z* ]] # True if $a starts with a "z" (wildcard matching).[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
function yesNo {# Prompts user with $1, returns true if response starts with y or Y or is empty stringread -e -p "$1 [Y/n] " YN
[[ "$YN" == y* || "$YN" == Y* || "$YN" == "" ]]}
像这样使用它:
$ if yesNo "asfd"; then echo "true"; else echo "false"; fi
asfd [Y/n] ytrue
$ if yesNo "asfd"; then echo "true"; else echo "false"; fi
asfd [Y/n] Ytrue
$ if yesNo "asfd"; then echo "true"; else echo "false"; fi
asfd [Y/n] yestrue
$ if yesNo "asfd"; then echo "true"; else echo "false"; fi
asfd [Y/n]true
$ if yesNo "asfd"; then echo "true"; else echo "false"; fi
asfd [Y/n] nfalse
$ if yesNo "asfd"; then echo "true"; else echo "false"; fi
asfd [Y/n] dddddfalse
这是一个更复杂的版本,它提供了指定的默认值:
function toLowerCase {echo "$1" | tr '[:upper:]' '[:lower:]'}
function yesNo {# $1: user prompt# $2: default value (assumed to be Y if not specified)# Prompts user with $1, using default value of $2, returns true if response starts with y or Y or is empty string
local DEFAULT=yesif [ "$2" ]; then local DEFAULT="$( toLowerCase "$2" )"; fiif [[ "$DEFAULT" == y* ]]; thenlocal PROMPT="[Y/n]"elselocal PROMPT="[y/N]"firead -e -p "$1 $PROMPT " YN
YN="$( toLowerCase "$YN" )"{ [ "$YN" == "" ] && [[ "$PROMPT" = *Y* ]]; } || [[ "$YN" = y* ]]}
像这样使用它:
$ if yesNo "asfd" n; then echo "true"; else echo "false"; fi
asfd [y/N]false
$ if yesNo "asfd" n; then echo "true"; else echo "false"; fi
asfd [y/N] ytrue
$ if yesNo "asfd" y; then echo "true"; else echo "false"; fi
asfd [Y/n] nfalse