2

我在 ksh 中有一个 Shell 脚本,在输入输入后,脚本要求输入 Y 表示是,输入 N 表示否,以便检查输入并继续。下面是脚本的那部分:

echo ""

YN=""
while [ "x$YN" != "xn" -a "x$YN" != "xN" -a "x$YN" != "xy" -a "x$YN" != "xY" ]; do
   echo -n "Please confirm (y/n): "
   read YN
done

if [ "x$YN" = "xn" -o "x$YN" = "xN" ]; then
   exit 0
fi

我无法理解

while [ "x$YN" != "xn" -a "x$YN" != "xN" -a "x$YN" != "xy" -a "x$YN" != "xY" ];

在这方面你能帮我吗..

4

1 回答 1

1

其实这应该写成:

while [ "$YN" != "n" -a "$YN" != "N" -a "$YN" != "y" -a "$YN" != "Y" ];

$YN但是对于某些 shell,如果变量为空,这将导致错误。因此,进行比较的安全方法是在比较两侧的双引号内附加一个虚拟字符(以便它们相互抵消),例如:

while [ "x$YN" != "xn" -a "x$YN" != "xN" -a "x$YN" != "xy" -a "x$YN" != "xY" ];

即使$YN是空的也不会中断。

于 2012-10-22T12:05:31.683 回答