Case语句fallthrough? [英] Case statement fallthrough?

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

问题描述

在流行的命令式语言,switch语句通常贯穿到一个新的水平,一旦一个case语句已经匹配。

例如:

  int类型的= 2;
开关(一)
{
   情况1:
      打印快速;
   案例2:
      打印棕色;
   案例3:
      打印狐狸精;
      打破;
   情况4:
      打印跳楼;
}

将打印棕色狐狸。

但同样code在bash

  A = 2
案例$ A在
2)
  回声快
  ;&安培;
2)
  回声棕色
  ;&安培;
3)
  回声FOX
  ;&安培;
4)
  回声跳楼
  ;&安培;
ESAC

仅打印棕色

我如何在bash case语句砸锅像第一个例子,其余条件?

(编辑:猛砸版本3.2.25的;&放大器;从维基声明()导致语法错误)

运行:

test.sh:

 #!/斌/庆典
A = 2
案例$ A在
1)
  回声快
  ;&安培;
2)
  回声棕色
  ;&安培;
3)
  回声FOX
  ;&安培;
ESAC

给出:


  

./ test.sh:6号线:附近意外的标记语法错误; ./test.sh:结果
  6号线:
;&安培;



解决方案

;&安培; ;;&安培; 经营者在bash 4.0中引入的,所以如果你想坚持一个五岁版本的bash,你要么必须重复code,或使用如果秒。

  IF((A == 1));然后回显快;科幻
如果((一个大于0&放大器;&放大器;一个与所述; = 2));然后回显褐色;科幻
如果((一个大于0&放大器;&放大器;一个与所述; = 3));然后回显狐狸;科幻
如果((A == 4));然后回显跃升;科幻

或者找一些其他的方式来实现实际的目标。

(在一个侧面说明,不要使用全大写变量名。你的风险覆盖特殊的shell变量或环境变量。)

In popular imperative languages, switch statements generally "fall through" to the next level once a case statement has been matched.

Example:

int a = 2;
switch(a)
{
   case 1:
      print "quick ";
   case 2: 
      print "brown ";
   case 3: 
      print "fox ";
      break;
   case 4:
      print "jumped ";
}

would print "brown fox".

However the same code in bash

A=2
case $A in
2)
  echo "QUICK"
  ;&
2)
  echo "BROWN"
  ;&
3)
  echo "FOX"
  ;&
4)
  echo "JUMPED"
  ;&
esac

only prints "BROWN"

How do I make the case statement in bash "fall through" to the remaining conditions like the first example?

(edit: Bash version 3.2.25, the ;& statement (from wiki) results in a syntax error)

running:

test.sh:

#!/bin/bash
A=2
case $A in
1)
  echo "QUICK"
  ;&
2)
  echo "BROWN"
  ;&
3)
  echo "FOX"
  ;&
esac

Gives:

./test.sh: line 6: syntax error near unexpected token ;' ./test.sh:
line 6:
;&'

解决方案

The ;& and ;;& operators were introduced in bash 4.0, so if you want to stick with a five year old version of bash, you'll either have to repeat code, or use ifs.

if (( a == 1)); then echo quick; fi
if (( a > 0 && a <= 2)); then echo brown; fi 
if (( a > 0 && a <= 3)); then echo fox; fi
if (( a == 4)); then echo jumped; fi

or find some other way to achieve the actual goal.

(On a side note, don't use all uppercase variable names. You risk overwriting special shell variables or environment variables.)

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

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