Running functions in the background

We have already seen in previous chapters that to run any command in the background, we have to terminate the command using &:

$ command &

Similarly, we can make the function run in the background by appending & after the function call. This will make the function run in the background so that the terminal will be free:

#!/bin/bash
dobackup()
{
    echo "Started backup"
    tar -zcvf /dev/st0 /home >/dev/null 2>&1
    echo "Completed backup"
}
dobackup &
echo -n "Task...done."
echo

Test the script as follows:

$ chmod +x function_17.sh
$ ./function_17.sh

Output:

Task...done.
Started backup
Completed backup

Command source and period (.)

Normally, whenever we enter a command, the new process gets created. If we want to make functions from the script to be made available in the current shell, then we need a technique that will run the script in the current shell instead of creating a new shell environment. The solution to this problem is using either the source or "."commands.

The commands source and "." can be used to run the Shell script in the current shell instead of creating a new process. This helps with declaring functions and variables in the current shell.

The syntax is as follows:

$ source filename [arguments]

Or:

$ . filename [arguments]

$ source functions.sh

Or:

$ . functions.sh

If we pass command-line arguments, these will be handled inside a script as $1, $2, and more:

$ source functions.sh arg1 arg2

Or:

$ ./path/to/functions.sh arg1 arg2

The source command does not create a new shell; but runs the Shell scripts in the current shell, so that all the variables and functions will be available in the current shell for usage.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset