Dynamic case statement in bash

前端 未结 5 1362
执念已碎
执念已碎 2020-12-20 01:25

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

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

5条回答
  •  情深已故
    2020-12-20 01:38

    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
    

提交回复
热议问题