缩短 if 语句检查匹配参数的时间

缩短 if 语句检查匹配参数的时间

我有一段代码可以完成它应该做的事情:

first_arg="$1";
if [ "$first_arg" != "patch" -a "$first_arg" != "major" -a "$first_arg" != "minor" -a "$first_arg" != "prerelease" ]; then
  echo "First argument needs to match a valid npm version argument (patch, minor, major, etc).";
  exit 1;
fi

它正在检查确保第一个参数是(补丁、主要、次要、预发行)之一。

但是,有没有更短/更简洁的方法来做到这一点?

答案1

您可以使用case,它可以在任何标准 shell 中工作:

case "$1" in
    patch|major|minor|prerelease) ;;
    *) echo "First argument needs to match a valid npm version argument (patch, minor, major, etc)." >&2; exit 1;;
esac

Bash/ksh/zsh 中的替代方法是使用正则表达式匹配:

if ! [[ $1 =~ ^(patch|major|minor|prerelease)$ ]]; then
    echo "First argument needs to match a valid npm version argument (patch, minor, major, etc)." >&2;
    exit 1;
fi

相关内容