IF-ELSE - Y|N 响应未按要求工作

IF-ELSE - Y|N 响应未按要求工作

我只是发现使用 for 循环很难实现以下目标。我们将非常感谢您的建议/帮助。谢谢

  1. 如果用户以大写或小写形式响应,则它应该接受并转换为大写形式。
  2. 当我尝试为“N”响应提供另一个 if 循环时,它不会触及该循环,而是给出第一个循环(ELSE 条件)本身的错误。

echo -n "IS THIS A PRODUCTION DATABASE. PLEASE RESPOND Y|N :- "
read RESPONSE
RSPN=$RESPONSE
if [ "${RSPN}" = "Y" ]
then
print "\n"
echo -n "PLEASE ENSURE A 7 YEARS RETENTION RMAN_FULL BACKUP TAKEN for $DBTD"
print "\n"
else
echo "ERROR: Cannot proceed as 7 Years backup not yet TAKEN for PRODUCTION database. Please take a 7 Years Retention backup and re-run the script again."
exit 1
print "\n"
fi
###############################################################
if [ "${RSPN}" = "N" ]
then
print "\n"
echo -n "PLEASE CHECK IF BACKUP IS REQUIRED BEFORE DECOMMISSIONING $DBTD
print "\n"
fi
###############################################################

输出--->

IS THIS A PRODUCTION DATABASE. PLEASE RESPOND Y|N :- N
ERROR: Cannot proceed as 7 Years backup not yet TAKEN for PRODUCTION database. Please take a 7 Years Retention backup and re-run the script again.

答案1

以下/bin/sh脚本坚持从用户那里获得有效响应(如果用户未提供以这两个字母(大写或小写)之一开头的一个y或一个或一个单词,它将再次询问)。n

while true; do
    printf 'IS THIS A PRODUCTION DATABASE? [y/n]: '
    read response

    case "$response" in
        [Yy]*) 
            printf 'PLEASE ENSURE A 7 YEARS RETENTION RMAN_FULL BACKUP TAKEN for %s\n' "$DBTD"
            break
            ;;
        [Nn]*)
            printf 'ERROR: Cannot proceed as 7 Years backup not yet TAKEN for PRODUCTION database. Please take a 7 Years Retention backup and re-run the script again.\n'
            printf 'PLEASE CHECK IF BACKUP IS REQUIRED BEFORE DECOMMISSIONING %s\n' "$DBTD"
            break
            ;;
        *) printf 'Invalid response "%s"\n' "$response"
    esac
done

如果用户输入N您的代码,则您似乎希望同时打印错误消息和“请检查”消息。这就是为什么当用户输入以 开头的单词时我输出这两条消息的原因n

如果您希望始终输出“PLEASE CHECK”消息,则只需将该printf行移至脚本末尾即可。

答案2

你可以用兼容的方式来做

if [ "${RSPN}" = "Y" ] || [ "${RSPN}" = "y" ]

或者如果你正在使用最近的 bash:

if [ "${RSPN^}" = "Y" ]

相关内容