Free Hosting Online for WorkStations

< Previous | Contents | Next >

Using Positional Parameters With Shell Functions

Just as positional parameters are used to pass arguments to shell scripts, they can also be used to pass arguments to shell functions. To demonstrate, we will convert the file_info script into a shell function:


file_info () {

# file_info: function to display file information if [[ -e $1 ]]; then

echo -e "\nFile Type:" file $1

echo -e "\nFile Status:" stat $1

else

echo "$FUNCNAME: usage: $FUNCNAME file" >&2 return 1

file_info () {

# file_info: function to display file information if [[ -e $1 ]]; then

echo -e "\nFile Type:" file $1

echo -e "\nFile Status:" stat $1

else

echo "$FUNCNAME: usage: $FUNCNAME file" >&2 return 1


fi

}

fi

}

Now, if a script that incorporates the file_info shell function calls the function with a filename argument, the argument will be passed to the function.

With this capability, we can write many useful shell functions that can not only be used in scripts, but also within our .bashrc files.

Notice that the PROGNAME variable was changed to the shell variable FUNCNAME. The shell automatically updates this variable to keep track of the currently executed shell function. Note that $0 always contains the full pathname of the first item on the com- mand line (i.e., the name of the program) and does not contain the name of the shell func- tion as we might expect.


Top OS Cloud Computing at OnWorks: