基于 if 条件的案例失败

Sma*_*gen 12 bash shell-script case

我正在寻找一种基于 bash 中 case 条件中的 if 条件发生失败的方法。例如:

input="foo"
VAR="1"

case $input in
foo)
    if [ $VAR = "1" ]; then

        # perform fallthrough

    else

        # do not perform fallthrough

    fi
;;
*)
    echo "fallthrough worked!"
;;
esac
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,如果变量VAR1,我希望案例条件执行失败。

ilk*_*chu 9

你不能。case失败的方法是;;;&(或;;&)替换分隔符。把它放在 if 中是一个语法错误。

您可以将整个逻辑写为常规条件:

if [ "$input" != "foo" ] || [ "$VAR" = 1 ]; then
    one branch ...
else   # $input = "foo" && $VAR != 1
    another branch...
fi
Run Code Online (Sandbox Code Playgroud)


gle*_*man 7

我建议重构你的逻辑:将“fallthrough”代码放入一个函数中:

fallthrough() { echo 'fallthrough worked!'; }

for input in foo bar; do
    for var in 1 2; do
        echo "$input $var"
        case $input in
            foo)
                if (( var == 1 )); then
                    echo "falling through"
                    fallthrough
                else
                    echo "not falling through"
                fi
            ;;
            *) fallthrough;;
        esac
    done
done
Run Code Online (Sandbox Code Playgroud)

产出

foo 1
falling through
fallthrough worked!
foo 2
not falling through
bar 1
fallthrough worked!
bar 2
fallthrough worked!
Run Code Online (Sandbox Code Playgroud)


Kus*_*nda 7

下面的脚本将您在这个意义上,我们测试试验“内向外” $var,然后再进行下通(用;&case视)$input

我们这样做是因为要不要的问题“进行下通”是真的只取决于$input,如果$var1。如果它是任何其他值,甚至不必问是否进行失败的问题。

#/bin/bash

input='foo'
var='1'

case $var in
    1)
        case $input in
            foo)
                echo 'perform fallthrough'
                ;&
            *)
                echo 'fallthough worked'
        esac
        ;;
    *)
        echo 'what fallthrough?'
esac
Run Code Online (Sandbox Code Playgroud)

或者,没有case

if [ "$var" -eq 1 ]; then
    if [ "$input" = 'foo' ]; then
        echo 'perform fallthrough'
    fi
    echo 'fallthough worked'
else
    echo 'what fallthrough?'
fi
Run Code Online (Sandbox Code Playgroud)


Sté*_*las 5

不是我会做的事情,但您可以通过以下方式实现:

shopt -s extglob # for !(*)
default='*'
case $input in
  (foo)
    if [ "$VAR" = 1 ]; then
      echo going for fallthrough
    else
      echo disabling fallthrough
      default='!(*)'
    fi ;;&

  ($default)
    echo fallthrough
esac
Run Code Online (Sandbox Code Playgroud)