在bash动态case语句 [英] Dynamic case statement in bash

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

问题描述

我试图找出如何在bash脚本创建一个动态的case语句。

I'm trying to figure out how to create a dynamic case statement in a bash script.

例如,假设我有一个awk语句包含以下内容的输出

For example, let's say I have the output of an awk statement with the following contents

red
green
blue

在这种情况下,输出可以在任何时间改变。

In this scenario, the output can change at any time.

我想如果一个值包括在此AWK输出则执行不同的逻辑。

I'm trying to then execute different logic if a value is included in this awk output.

因此​​,如果上述数据在$列表中,那么我会在概念上喜欢做的事是这样的:

So if the data above is in $list, then I'd conceptually like to do something like:

case "${my_var}" in
    $list)
        .....
    something_else)
        .....
esac

我试图用它来构建一个动态的自定义选项卡完成功能(见的​​http://www.debian-administration.org/article/An_introduction_to_bash_completion_part_2对于一些背景)。

任何想法?

感谢。

推荐答案

A 情况语句可能是不适合这份工作的合适工具。如果存储在 AWK 输出数组,那么你可以遍历数组找到,如果选择的是在里面,作为奖励可以找出哪些指标是,了。

A case statement is probably not the right tool for the job. If you store the awk output in an array then you can loop through the array to find if a choice is in it, and as a bonus can figure out which index that is, too.

#!/bin/bash

# Store command output in an array so each word is a separate array item.    
list=($(echo $'red\ngreen\nblue'))
my_var=blue

for ((i = 0; i < ${#list}; i++)); do
    if [[ ${list[$i]} = $my_var ]]; then
        echo "found at index $i"
        break
    fi
done

if ((i == ${#list})); then
    echo "not found"
fi

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

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