【问题标题】:Better way then having multiple elif statement更好的方法然后有多个 elif 语句
【发布时间】:2018-11-19 20:16:07
【问题描述】:

我有一个名为 file.txt 的文件,其中包含一些从 1 到 100 的随机数。因此,脚本会读取该文件并执行一堆命令并打印一些语句。

实现结果的一种方法可能是这样的,但在脚本中包含 100 个 ifelif 语句看起来不太好。

for i in `cat file.txt`; do
  echo "Displaying" $i
    if [[ $i = 1 ]]; then
        echo "blah blah blah for" $i
        command1
        command2
    elif [[ $i = 2 ]]; then
        echo "blah blah blah for" $i
        command3
        command4
        command5
    elif [[ $i = 3 ]]; then
        echo "blah blah blah for" $i
        command6
        command7
    elif [[ $i = 4 ]]; then
        echo "blah blah blah for" $i
        command8
        command9
        command10
    elif [[ $i = 5 ]]; then
        echo "blah blah blah for" $i
        command11
        command12
        command13
        command14
    elif [[ $i = 6 ]]; then
        echo "blah blah blah for" $i
        command15

        ....
        ....
        ....
        ....
        ....
        ....
    elif [[ $i = 99 ]]; then
        echo "blah blah blah for" $i
        command310
        command311
        command312
        command313
        command314
    elif [[ $i = 100 ]]; then
        echo "blah blah blah for" $i
        command315
    fi
done

在 bash 上有没有更好或更聪明的方法来做这些

【问题讨论】:

  • 我会从 case 声明 case $i in 1) ... ;; 2) ... ;; ... ;; 99) ... ;; esac 开始。
  • @JosephLi 在elifs 之间用独角兽表情符号写 cmets 会很好看

标签: bash if-statement


【解决方案1】:

我的建议是使用case 声明。它是编程中称为switch statement 的bash 版本。它们通常比 if-then-else 语句更快,因为它们很可能通过查找表或哈希列表来实现。

此外,优化的实现可能比替代方案执行得更快,因为它通常是通过使用索引分支表来实现的。例如,根据单个字符的值来决定程序流,如果正确实施,将比替代方案更有效,从而大大减少指令路径长度。当这样实现时,switch 语句本质上就变成了一个完美的散列。

来源:Wikipedia

可以在这里找到一个有趣的比较:Which is faster of two case or if?

为了解决你的代码,你是表单的循环

for i in $(cat file); do
  ...
done

应该重写。当您逐字阅读文件时,您应该编写如下内容:

while read -r line; do
   for i in $line; do
     ...
   done
done < file

你的 if-then-else 然后被改写为:

case "$i" in
   1) command1; command2; command3 ;;
   2) command4; command5; command6 ;;
   ...
   100) command315; command316;;
esac

【讨论】:

  • Bash case 语句即使在可能的情况下也没有优化(并且由于选项受参数扩展的影响,这很可能是不可能的。所以它们并不快,但它们更容易写(和读)。它们基本上快一点,因为它们不需要解释 [/[[ 命令。
  • @rici 根据stackoverflow.com/questions/20018037/… 有明显区别。
  • 是的,但是 [ 命令的区别比 [[ 内置命令要明显得多。它与查找表或索引查找无关。
  • @rici 在我当前的系统上,使用 case 而不是 [[ ... ]]] 仍然有 1/3 的加速
  • 你的意思是它快了 33%,对吧?哈希表会快得多,因为它不需要多次测试。
【解决方案2】:

case的经典案例:

case "$i" in
    1)
        echo "blah blah blah for" $i
        command1
        command2
        ;;
    […]
    *)
        echo "Unhandled value $i" >&2
        exit 2
esac

除此之外:

【讨论】:

    猜你喜欢
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2023-02-07
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多