BASH 不是万一

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21919182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:39:01  来源:igfitidea点击:

BASH Not In Case

bashcase

提问by ehime

Hey guys I'm trying to figure out a sane way to do a NOT clause in a case. The reason I am doing this is for transcoding when a case is met, aka if I hit an avi, there's no reason to turn it into an avi again, I can just move it out of the way (which is what the range at the base of my case shoulddo). Anyway, I have some protocode that I wrote out that kind of gives the gist of what I am trying to do.

嘿伙计们,我正试图找出一种在案例中使用 NOT 子句的理智方法。我这样做的原因是为了在遇到情况时进行转码,也就是如果我击中了 avi,就没有理由再次将其转换为 avi,我可以将其移开(这是我的案子应该这样做)。无论如何,我有一些 我写出来的原型代码,它给出了我想要做的事情的要点。

#!/bin/bash
for i in $(seq 1 3); do 

    echo "trying: $i"

    case $i in
        ! 1)    echo "1" ;;     # echo 1 if we aren't 1
        ! 2)    echo "2" ;;     # echo 2 if we aren't 2
        ! 3)    echo "3" ;;     # echo 3 if we aren't 3
        [1-3]*) echo "! $i" ;;  # echo 1-3 if we are 1-3
    esac

    echo -e "\n"

done

expected results would be something like this

预期结果将是这样的

2 3 ! 1
1 3 ! 2
1 2 ! 3

Help is appreciated, thanks.

感谢帮助,谢谢。

回答by Charles Duffy

This is contrary to the design of case, which executes only the first match. If you want to execute on multiple matches (and in your design, something which is3would want to execute on both 1and 2), then caseis the wrong construct. Use multiple ifblocks.

这与 的设计相反case,它只执行第一场比赛。如果你想在多个匹配执行(并在设计中,一些东西,3想对双方执行12),然后case是错误的结构。使用多个if块。

[[ $i = 1 ]] || echo "1"
[[ $i = 2 ]] || echo "2"
[[ $i = 3 ]] || echo "3"
[[ $i = [1-3]* ]] && echo "! $i"

Because case only executes the first match, it only makes sense to have a single "did-not-match" handler; this is what the *)fallthrough is for.

因为 case 只执行第一个匹配,所以只有一个“did-not-match”处理程序才有意义;这就是*)失败的目的。

回答by kojiro

You can do this with the extglob extension.

您可以使用 extglob 扩展来执行此操作。

$ shopt -s extglob
$ case foo in !(bar)) echo hi;; esac
hi
$ case foo in !(foo)) echo hi;; esac
$