0

我正在尝试验证用户对我正在编写的一个小脚本的输入,该脚本检查是否应该有:2 个参数,第一个参数应该是“mount”或“unmount”

我有以下内容:

if [ ! $# == 2 ] || [ $1 != "mount" -o $1 != "unmount" ]; then

然而,在满足我想要的条件时似乎有点过分。例如与当前 || 运算符,没有任何东西可以通过验证器,但是如果我使用 && 运算符,一切都可以。

if [ ! $# == 2 ] && [ $1 != "mount" -o $1 != "unmount" ]; then

有人可以帮我解决这个问题吗?

这是整个块和预期用途

if [ ! $# == 2 ] || [ $1 != "mount" -o $1 != "unmount" ]; then
  echo "Usage:"
  echo "encmount.sh mount remotepoint       # mount the remote file system"
  echo "encmount.sh unmount remotepoint   # unmount the remote file system"
  exit
fi
4

1 回答 1

1

你可以这样做:

if [ "$#" -ne 2 ] || [ "$1" != "mount" -a "$1" != "unmount" ]; then
    echo "Usage:"
    echo "encmount.sh mount remotepoint       # mount the remote file system"
    echo "encmount.sh unmount remotepoint   # unmount the remote file system"
    exit -1
fi
echo "OK" 

您的测试中有一个小的逻辑错误,因为如果$1不等于"mount"和,您应该进入使用分支"unmount"-eq此外,您应该使用and运算符比较数字-ne请参阅此处),或使用(( )).

请注意,您应该在test( [ ])中引用变量

您还可以像这样组合这两个表达式:

if [ "$#" -ne 2 -o \( "$1" != "mount" -a "$1" != "unmount" \) ]; then

如果你有 bash,你也可以使用以下[[ ]]语法:

if [[ $# -ne 2 || ( $1 != "mount" && $1 != "unmount" ) ]]; then
于 2013-02-27T08:10:47.083 回答