When I pass in 2009 as a arg to this shell function it returns 0, why?
isyear()
{
case $arg in
[0-9][0-9][0-9][0-9]) NUM=1 ;;
*) NUM=0 ;;
esac
echo $arg
}
When I pass in 2009 as a arg to this shell function it returns 0, why?
isyear()
{
case $arg in
[0-9][0-9][0-9][0-9]) NUM=1 ;;
*) NUM=0 ;;
esac
echo $arg
}
You likely mean $1
instead of $arg
. $arg
isn't defined anywhere and $1
is the first argument to the function.
Do you mean to use return
instead of echo
?
return [n] Causes a function to exit with the return value specified by n. If n is omitted, the return status is that of the last command executed in the function body.
Two typos: First of all you need to use $1 not $arg to get the first parameter of the function. Secondly I think you meant to echo $NUM rather than the passed-in argument!
isyear() {
case $1 in
[0-9][0-9][0-9][0-9]) NUM=1 ;;
*) NUM=0 ;;
esac
echo $NUM
}
You might also consider reworking it like this:
#!/bin/bash
isyear() {
case $1 in
[0-9][0-9][0-9][0-9]) return 1 ;;
*) return 0 ;;
esac
}
isyear cheese
if [ "$?" -eq "1" ]; then
echo "Yes, it is a year!"
else
echo "Darn!"
fi
isyear 2009
if [ "$?" -eq "1" ]; then
echo "Yes, it is a year!"
else
echo "Darn!"
fi