带AND运算符的if语句 [英] An if statement with AND operator

查看:43
本文介绍了带AND运算符的if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试与变量进行字符串比较,我尝试根据

Trying to comparisons with a variable against strings, i tried code as per the solution from https://unix.stackexchange.com/questions/67898/using-the-not-equal-operator-for-string-comparison

if [ "$ACTION" != "dry" ] && [ "$ACTION" != "prune" ]
then
    echo "Invalid"
fi

这对我不起作用,我没有收到任何错误消息,就像只是跳过了代码块一样.

This does not work for me, i get no error messages it's like it just skips the code block.

我也按照这里的答案尝试过这样对具有多个条件的if语句进行重击

I have also tried like this as per answer here Bash if statement with multiple conditions

if [[ "$ACTION" != "dry" && "$ACTION" != "prune" ]]
then
    echo "Invalid"
fi

如果$ ACTION不是"dry",即使它的修剪",它也会回显"Invalid"

This echoes "Invalid" if $ACTION is anything other than "dry", even if its "prune"

有什么建议吗?

编辑

完整代码

OPTIND=1
while getopts "b:a:" option
do
    case "${option}"
    in
        b) MERGE_BRANCH=${OPTARG};;
        a) ACTION=${OPTARG};;
    esac
done

if [[ "$ACTION" != "dry" && "$ACTION" != "prune" ]]
then
    echo "Invalid"
fi

shift $((OPTIND-1))
[ "$1" = "--" ] && shift

(( 1 <= ${#} )) || { echo "missing mandatory argument" 2>&1 ; exit 1;     };

推荐答案

好吧,在大多数情况下,出现这样的命令的情况下,使用 case 提供了一种更可维护的解决方案,因为在您的生命周期中您将要更改动作名称,处理新情况等的脚本:

Well, in most situations where such a command arises, using case provides a more maintainable solution, because during the life cycle of your script you will want to change action names, deal with new situations, and so on:

case "$ACTION" in 
  ("dry"|"prune") 
    : # Insert appropriate code
  ;;
  (*)
    echo Invalid
  ;;
esac

第二,在这种情况下,无需使用 [[>语法

Second, there is no need to use the [[ syntax in this case

if [ "$ACTION" != dry ] && [ "$ACTION" != prune ]; then
  echo Invalid
fi

在这种情况下,

就足够了.要测试一切正常,可以添加一个 else 分支:

if [ "$ACTION" != dry ] && [ "$ACTION" != prune ]; then
  echo Invalid
else
  echo Valid
fi

这篇关于带AND运算符的if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆