Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable as case pattern in Bash

Tags:

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 "$1" in     $test)         echo "matched"         ;;     *)         echo "didn't match"         ;; esac 

I've tried this with assigning $test as aaa|bbb|ccc, (aaa|bbb|ccc), [aaa,bbb,ccc] and several other combinations. I also tried these as the pattern in the case statement: @($test), @($(echo $test)), $($test). Also no success.

For clarity, I would like the variable to represent multiple patterns like this:

case "$1" in     aaa|bbb|ccc)         echo "matched"         ;;     *)         echo "didn't match"         ;; esac 
like image 658
siebz0r Avatar asked Nov 06 '12 15:11

siebz0r


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do you write a case statement in bash?

The case statement starts with the case keyword followed by the $variable and the in keyword. The statement ends with the case keyword backwards - esac . The script compares the input $variable against the patterns in each clause until it finds a match.

What is ESAC in bash?

esac statement is to give an expression to evaluate and to execute several different statements based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.

What is difference between $@ and $* variables in bash?

There is no difference if you do not put $* or $@ in quotes. But if you put them inside quotes (which you should, as a general good practice), then $@ will pass your parameters as separate parameters, whereas $* will just pass all params as a single parameter.


1 Answers

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 ddd ; do     echo -n "$x "     case "$x" in         $test) echo Matches.         ;;         *) echo Does not match.     esac done 
like image 161
choroba Avatar answered Oct 09 '22 04:10

choroba