Functions in UNIX Shell
Functions in any programming language help you break down the script into logical subsections. UNIX shell lets you use functions.
Let's look at an example function called hello. Here is how we define hello function:
[user19@localhost ~]$ hello() {
> echo hello. please enter your nme
> read name
> echo welcome $name
> }
To call function hello, simply call it by its name:
[user19@localhost ~]$ hello
hello. please enter your nme
user1
welcome user1
You can list the functions that you have defined using set command.
[user19@localhost ~]$set
tmpid=509
hello ()
{
echo hello. please enter your nme;
read name;
echo welcome $name
}
To undefine the function, use unset command:
[user19@localhost ~]$ unset hello
Functions are stored in memory and therefore are faster than a regular script. Any script or program with the same name as the function will have lesser precedence.
Let's see how we can use a function in a script. Let's define the function in a separate script called func.sh and use it in main.sh.
[user19@localhost ~]$ cat func.sh
hello() {
echo Please enter your name
read name
echo Hi $name
}
[user19@localhost ~]$ cat main.sh
echo am going to call a function
echo before calling load the func
. ./func.sh
echo calling
hello
Now, when we run main.sh:
[user19@localhost ~]$ sh main.sh
am going to call a function
before calling load the func
calling
Please enter your name
user1
Hi user1
Let's look at an example function called hello. Here is how we define hello function:
[user19@localhost ~]$ hello() {
> echo hello. please enter your nme
> read name
> echo welcome $name
> }
To call function hello, simply call it by its name:
[user19@localhost ~]$ hello
hello. please enter your nme
user1
welcome user1
You can list the functions that you have defined using set command.
[user19@localhost ~]$set
tmpid=509
hello ()
{
echo hello. please enter your nme;
read name;
echo welcome $name
}
To undefine the function, use unset command:
[user19@localhost ~]$ unset hello
Functions are stored in memory and therefore are faster than a regular script. Any script or program with the same name as the function will have lesser precedence.
Let's see how we can use a function in a script. Let's define the function in a separate script called func.sh and use it in main.sh.
[user19@localhost ~]$ cat func.sh
hello() {
echo Please enter your name
read name
echo Hi $name
}
[user19@localhost ~]$ cat main.sh
echo am going to call a function
echo before calling load the func
. ./func.sh
echo calling
hello
Now, when we run main.sh:
[user19@localhost ~]$ sh main.sh
am going to call a function
before calling load the func
calling
Please enter your name
user1
Hi user1
Comments
Post a Comment