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
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
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
Thanks for the kind words. Just for that, here's another example.
This function is a wrapper around tar being used to copy a source
directory to a destination. You need to be careful about passing
strings to a ksh function. This function's argument is a
string with two directories. I use set to break $1 into two
arguments, and I make sure the directories exist before the copy
takes place.
Regards,
Ed
# copy $1 (src) to $2 (destination)
function cp_directory {
set $1 # break $1 argument
if [ ! -d $1 ]
then
return 1 # source doesn't exist
fi
if [ ! -d $2 ]
then
return 1 # destination doesn't exist
fi
cd $1; tar -cf - .|(cd $2; tar -xf - ); return $?
}
cp_directory "/usr/eds/olddir /jet/eds/newdir"
if [ $? -eq 0 ]
then
echo "copy complete"
else
echo "copy failure"
fi
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.