bash 中的动态 case 语句 [英] Dynamic case statement in bash
问题描述
我正在研究如何在 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.
因此,如果上面的数据在 $list 中,那么从概念上讲,我想执行以下操作:
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 了解一些背景.
I'm trying to use this to build a dynamic custom tab completion function (see http://www.debian-administration.org/article/An_introduction_to_bash_completion_part_2 for some background).
有什么想法吗?
谢谢.
推荐答案
case
语句可能不是完成这项工作的正确工具.如果您将 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
green
blue'))
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屋!