Typically, when you write a shell script, you'll find that the same piece of code is used in multiple places. It doesn't matter if it's just a small piece of code. But it's hard to rewrite chunks of code multiple times in a shell script. The bash shell supports user-defined functions, which solves this challenge. Talk about how the function is played in the shell today.
The bash Shell has a feature that allows us to do this. A function is a block of code that can be named and reused anywhere in the code. If we use this block of code in our script, we can simply use the Assigned function name (this process is called the call function). Next we'll talk about the creation and use of functions:
Takes the keyword function, followed by the name of the functions assigned to the code block:
Function name {
Commands
}
The Name property defines the unique name assigned to the function. You must assign a unique name to each function defined in the script.
Commands is one or more bash shell commands that make up a function. When the function is called, the Bash Shell executes the command in the order in which it appears in the function, as in the normal script.
- Name () {commands}
- Using functions in a script, you can specify the function name directly on the command line, just as you would with other shell commands:
#!/bin/bash
#using a function in a script
function Func1 {
echo "This was an example of a function"
}
Count=1
While [$count-le 5]
Do
Func1
count=$[$count + 1]
Done
echo "This is the end of the loop"
Func1
echo "Now this is the end of the script"
Shell creation functions and reference functions