Hi,
I'm completely new to shell and I'm trying to include a case where the function's arg #1 is greater or equal 12 then it should return 1. But the below doesn't work.
case $1 in
-ge 12) NUM=1 ;;
*) NUM=0 ;;
esac
echo $NUM
Hi,
I'm completely new to shell and I'm trying to include a case where the function's arg #1 is greater or equal 12 then it should return 1. But the below doesn't work.
case $1 in
-ge 12) NUM=1 ;;
*) NUM=0 ;;
esac
echo $NUM
Do you have to use case
for some reason? If not, if
seems more natural:
if [[ $1 -ge 12 ]]; then
NUM=1
else
NUM=0
fi
echo $NUM
With case
, bash performs arithmetic expansion on both word and pattern, so you could write
case 1 in
$(( $1 >= 12 )) ) NUM=1 ;;
$(( $1 >= 7 )) ) NUM=2 ;;
*) NUM=0 ;;
esac
Beauty is in the eye of the beholder.
Case needs to take a pattern expression, e.g. a string.
I either recommend using a simple if statement:
if [[ $1 -ge 12 ]]; then
NUM=1
else
NUM=0
fi
Or express the branches in pattern expressions:
case "$1" in
[0-9]) NUM=1 ;;
1[0-2]) NUM=1 ;;
*) NUM=0 ;;
echo $NUM
The case statement does not interpret operators like -ge. From the bash man page:
case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac
A case command first expands word, and tries to match it
against each pattern in turn, using the same matching rules as
for pathname expansion (see Pathname Expansion below).
You should use a conditional expression in an if
statement.
You want to use the program /usr/bin/test
:
if test "$1" -ge 12; then NUM=1; else NUM=2; fi