Export a bash function as command
You can use a function written in bash script to use like any other Unix/Linux command. This function can take command line arguments and return a value as exit code similar to standard commands. In the following example, we try to identify if a directory exists with the given name. The function returns 1 if a directory exists. Otherwise returns 0. You can copy the following piece of code and keep in a script or paste it on the console.
function isdir()
{
echo REQ isdir $1
if [ -d "$1" ]; then
return 1
else
return 0
fi
}
export -f isdir
Now let us invoke this as a standard command and examine the return code.
[neo@techpulp ~]$ ls dir1 dir2 file1 file2 [neo@techpulp ~]$ isdir dir1 REQ isdir dir1 [neo@techpulp ~]$ echo $? 1 [neo@techpulp ~]$ isdir dir99 REQ isdir dir99 [neo@techpulp ~]$ echo $? 0
If you are using this code in a script, you can use it as shown below.
function isdir()
{
echo REQ isdir $1
if [ -d "$1" ]; then
return 1
else
return 0
fi
}
export -f isdir
isdir dir1
if [ "$?" == "0" ]; then
echo Please specify an existing directory
exit 0
fi
echo Continuing.. please wait

