【问题标题】:a more elegant way to do nested if then conditions一种更优雅的嵌套 if then 条件的方法
【发布时间】:2014-02-13 17:58:11
【问题描述】:

我想通过两组检查来推送我的输入参数。这些检查中的每一个都是一个函数。所以 case 不起作用,因为在 KSH.Case 中,在满足第一个条件后会“esac”。

    die () {
        echo "ERROR: $*. Aborting." >&2
        exit 1
    }

    var=$1
    var1=$2
    [  -z "$var1" ] && var1=$var
    echo "var is $var . Var1 is $var1 "


    # test $var1 != $var2 ||
    dtc() {
  # small function where I am checking if the input parameter is a valid date
    }

    vlc(){
# function where I am checking if the input parameters year is after 2012, because earlier years cannot exist 
}

if dtc  $var && dtc  $var1
then
  if vlc $var && vlc $var1
  then
  stuff
  else
  die "message"
  fi
else
  die "message"
fi

嵌套的 if 看起来有点笨拙。如果有更优雅的方式将其传达给 shell。

【问题讨论】:

    标签: shell if-statement conditional case logical-operators


    【解决方案1】:

    改进缩进将大大有助于代码的可读性。

    如果您的die 消息不同,那么您别无选择。如果它们相同,则可以组合条件:

    如果不是所有的命令都成功,你就想死,你可以这样写

    dtc "$var" && dtc "$var1" &&
    vlc "$var" && vlc "$var1" || die "message"
    # OK, all passed
    stuff
    

    if-else 的一个风格提示是把 shorter 块放在首位

    if ! { dtc "$var" && dtc "$var1"; }
    then
        die "message 1"
    else
        if ! { vlc "$var" && vlc "$var1"; }
        then
            die "message 2"
        else
            we will do 
            lots of stuff 
            here
        fi
    fi
    

    当然还有封装代码的函数

    stuff() {
        we will do 
        lots of stuff
        here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      相关资源
      最近更新 更多