Here are 4 other examples.
Regards,
Ed
1.
# yesorno: This function takes one argument and if the
# value is Y or y returns 1 else it returns 0. Pressing
# <CR> returns 0;
# usage: $(yesorno $answer)
function yesorno {
case $1 in
y|Y) echo 1;;
*)
echo 0;;
esac
} # end yesorno
printf "Answer the question: Y/N: "
read answer
ret_val=$(yesorno $answer)
echo $ret_val
2.
# user_exist: This function takes an argument which is the
# user id, greps the first field of /etc/passwd and sets
# the exit code, 1 if user exists and 0 if not.
# sample the exit code $? from calling program.
function user_exist
{
if grep "^$1:" /etc/passwd > /dev/null 2>&1
then return 1
else return 0
fi
} # end user_exist
Sample the exist code immediately after returning from the user_exist
function:
loginame=alexb
user_exist $loginame
if [ "$?" -eq 0 ]
then printf "User %s does NOT exist\n" $loginame
else printf "User %s exists\n" $loginame
fi
3.
# down_shift: This function takes one argument, downshifts it
# to lowercase, and returns the string
# usage: string=$(down_shift $string)
function down_shift {
local string
string=`echo $1 | tr '[A-Z]' '[a-z]'`
# alternate tr command
#string=`echo $1 | tr "[:upper:]" "[:lower:]"`
echo $string
} # end down_shift
string="ALLLOWERCASE"
string=$(down_shift $string)
echo $string
4.
# is_digit: This function matches an all digits regular expression
# against an argument and returns 1 if the argument is digits else 0
# if isn't.
# Note the use of nawk. Use gawk for the Bash shell.
function is_digit
{
echo $1|nawk ' { if ($0 ~ /^[0-9]+$/)
print 1
else
print 0 } '
} # end is_digit
num="345"
ret_val=$(is_digit $num)
echo $ret_val