【问题标题】:Find out which of the multiple conditions is true找出多个条件中的哪一个为真
【发布时间】:2017-06-08 07:13:46
【问题描述】:

我有一个脚本,它将检查 if 语句中的多个条件并在其为真时运行所需的命令。

  if [ ! -f /tmp/a ] && [ ! -f /tmp/b  ]; then
        touch /tmp/c  else 
        echo "file exists"  fi

我现在需要知道多个条件中哪一个是正确的。 例如:曾经存在的 /tmp/a 或 /tmp/b。有没有办法在我的 else 条件下得到它?

【问题讨论】:

    标签: bash shell if-statement multiple-conditions


    【解决方案1】:

    由于您的if 使用复合条件,else 无法确定复合条件的哪一部分失败。你可以这样重写你的代码:

    a_exists=0
    b_exists=0
    [[ -f /tmp/a ]] && a_exists=1 # flag set to 1 if /tmp/a exists
    [[ -f /tmp/b ]] && b_exists=1 # flag set to 1 if /tmp/b exists
    if [[ $a_exists == 0 && $b_exists == 0 ]]; then
      touch /tmp/c
    else
      [[ $a_exists == 1 ]] && echo "a exists"
      [[ $b_exists == 1 ]] && echo "b exists"
    fi
    

    上面的代码可以用Bash算术运算符(( ... ))写得更简洁:

    a_exists=0
    b_exists=0
    [[ -f /tmp/a ]] && a_exists=1 # flag set to 1 if /tmp/a exists
    [[ -f /tmp/b ]] && b_exists=1 # flag set to 1 if /tmp/b exists
    if !((a_exists + b_exists)); then
      touch /tmp/c
    else
      ((a_exists)) && echo "a exists"
      ((b_exists)) && echo "b exists"
    fi
    

    【讨论】:

    • 你能解释一下吗?我很困惑:)
    • 基本上,我们使用两个基于文件存在设置的标志。然后,if-else 块将使用这些标志,而不必担心它们是如何设置的。
    • 哦,对我来说,我们可以设置 [[ ]] 而不设置 if 并且还设置这样的标志,这对我来说是新的。非常感谢。
    【解决方案2】:

    这听起来就像有一天会有两个以上的文件要检查。使用循环:

    i_am_happy=yeah
    for f in a b
    do
        if [[ ! -f /tmp/$f ]]
        then
          echo "Criminy! No $f in tmp!"  # or what else you would like to do.
          i_am_happy=nope
        fi
    done
    [[ i_am_happy == nope ]] && touch /tmp/c
    

    【讨论】:

      猜你喜欢
      • 2012-02-24
      • 1970-01-01
      • 2016-11-30
      • 2016-05-08
      • 2021-11-21
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      相关资源
      最近更新 更多