When your scripts get bigger and bigger, things can get very messy. To overcome this problem, you can use bash functions. The idea behind functions is that you can reuse parts of your scripts, which in turn produces better organized and readable scripts.
The general syntax of a bash function is as follows:
function_name () {
<commands>
}
Let's create a function named hello that prints out the line "Hello World". We will put the hello function in a new script named fun1.sh:
elliot@ubuntu-linux:~$ cat fun1.sh
#!/bin/bash
hello () {
echo "Hello World"
}
hello # Call the function hello()
hello # Call the function hello()
hello # Call the function hello()
Now make the script executable and run it:
elliot@ubuntu-linux:~$ chmod a+x fun1.sh
elliot@ubuntu-linux:~$ ./fun1.sh
Hello World
Hello World
Hello World
The script outputs the line "Hello World" three times to the terminal. Notice that we called (used) the function hello...