Using variable as case pattern in Bash

前端 未结 3 798
旧巷少年郎
旧巷少年郎 2020-12-31 00:29

I\'m trying to write a Bash script that uses a variable as a pattern in a case statement. However I just cannot get it to work.

Case statement:

case          


        
相关标签:
3条回答
  • 2020-12-31 00:46

    (Updated): here's something a bit different, but I hope it works for what you need it for:

    #!/bin/bash
    
    pattern1="aaa bbb ccc"
    pattern2="hello world"
    test=$(echo -e "$pattern1\n$pattern2" | grep -e $1)
    
    case "$test" in
        "$pattern1")
            echo "matched - pattern1"
            ;;
        "$pattern2")
            echo "matched - pattern2"
            ;;
        *)
            echo "didn't match"
            ;;
    esac
    

    This makes use of grep to do the pattern matching for you, but still allows you to specify multiple pattern sets to be used in a case-statement structure.

    For instance:

    • If either aaa, bbb, or ccc is the first argument to the script, this will output matched - pattern1.
    • If either hello or world is the first argument, this will output matched - pattern2.
    • Otherwise it will output didn't match.
    0 讨论(0)
  • 2020-12-31 00:48

    You can use the extglob option:

    #! /bin/bash
    
    shopt -s extglob         # enables pattern lists like +(...|...)
    test='+(aaa|bbb|ccc)'
    
    for x in aaa bbb ccc ffffd ; do
        echo -n "$x "
        case "$x" in
            $test) echo Matches.
            ;;
            *) echo Does not match.
        esac
    done
    
    0 讨论(0)
  • 2020-12-31 01:02

    using eval also works:

    eval 'case "$1" in
    
        '$test')
            echo "matched"
            ;;
        *)
            echo "did not match"
            ;;
    esac'
    
    0 讨论(0)
提交回复
热议问题