2
I'd like to have something like the following:
#!/bin/sh
# ... other stuff ...
# some relatively static possibilities (srsp):
srsp='this|or|that|the|other'
# more other stuff
case $something in
$srsp) # <- problem is here
do_something # or maybe nothing
;;
this|or|that|the|other);; # this would work, but loses the benefit of a variable
*)
# anything not in my list is an error:
echo "Sorry, I don't recognize $something as one of $srsp" >&2
exit 1;;
esac
do_something | egrep "blah($srsp)thing" # or whatever
The problem is, having $srsp
there only matches the whole string (if $something
was exactly the string "this|or|that|or|some|other|stuff"
, it would match and call do_something
), rather than any of this
or or
or that
... and so forth: the values I actually want to match.
If I put that literal string in the case statement (my "this would work" line), it matches what I want it to match, but I'm trying to keep this DRY, and I need the same set of strings in the regular expression I use later. (Side note: I understand that what's possible in a case
match and what's possible in a regular expression can differ dramatically, but in my particular situation, they're compatible with both. It really is just letters in the individual components, no wildcards, just the |
, which exists as a special case in both systems.)
So, is there a way to do this? Especially without wrapping the whole case statement inside an eval or something? I'd like to still keep it in a case statement, because I have other stuff going on. (I'm sure I could implement a workaround by re-structuring and using egrep as my match test (if echo $something | egrep "^($srsp)$" > /dev/null
, or some such). This question is about trying to find a way to do it without having to resort to that. Or definitively knowing that it can't be done would also be a valid answer.)
(Or should I switch to common-lisp? ;) )
For my needs, I'd be happy with sh
or bash
for sure, and possibly zsh
, though if there's a way to do this in a maximally-portable way (i.e. sh
), that would make for a better answer, IMHO.
Well, the first option here doesn't really work for me, because it loses the compatibility with egrep (and similar), which was a big part of the point. Your latter suggestion does at least give me a match, though, and that works in this case. (It would in principal be nice to not have to invert the case, but for my purposes, it'll do.) Thanks! – lindes – 2015-03-03T21:39:24.503