Sample Header Ad - 728x90

How can I use a variable as a case condition?

29 votes
7 answers
46138 views
I am trying to use a variable consisting of different strings separated with a | as a case statement test. For example: string="\"foo\"|\"bar\"" read choice case $choice in $string) echo "You chose $choice";; *) echo "Bad choice!";; esac I want to be able to type foo or bar and execute the first part of the case statement. However, both foo and bar take me to the second: $ foo.sh foo Bad choice! $ foo.sh bar Bad choice! Using "$string" instead of $string makes no difference. Neither does using string="foo|bar". I know I can do it this way: case $choice in "foo"|"bar") echo "You chose $choice";; *) echo "Bad choice!";; esac I can think of various workarounds but I would like to know if it's possible to use a variable as a case condition in bash. Is it possible and, if so, how?
Asked by terdon (251585 rep)
Oct 6, 2015, 12:35 PM
Last activity: Aug 26, 2022, 06:01 PM