Of course you can use a function, but the function should print the pattern you want to match as a glob. That's what case
operates on.
is_one () {
echo 1
}
case $var in
"$(is_one)") echo 'It matched!';;
*) echo ':-(';;
esac
Perhaps a better design if you really want to use a function is to write a one which (doesn't contain syntax errors and) returns a non-zero exit code on failure. In this particular case, encapsulating it in a function doesn't really make much sense, but of course you can:
is_one () {
[ "$1" -eq 1 ]
}
if is_one "$var"; then
echo 'It matched!"
else
echo ':-('
fi
Notice the non-optional spaces inside [...]
and also the quoting, and the use of a parameter instead of hard-coding a global variable.
Furthermore, note that -eq
performs numeric comparisons, and will print an unnerving error message if $var
is not numeric. Perhaps you would prefer to use [ "$1" = "1" ]
which performs a simple string comparison. This is also somewhat closer in semantics to what case
does.