Running functions in the background in Linux bash script

April 28, 2021

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:

    echo "Started backup" 
    tar -zcvf /dev/st0 /home >/dev/null 2>& 1 
    echo "Completed backup" 
dobackup & 
echo -n "Task...done." 

Test the script as follows:

$ chmod +x
$ ./

This should produce the following output:


Task...done.Started backupCompleted 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 you can use the following:

$ . filename [arguments]  
$ source

Or you could use this:

$ .

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

$ source arg1 arg2

Or you could enter the following:

$ ./path/to/ arg1 arg2

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

Related Articles

Calculating and reducing the runtime of a script

In this article, we are going to learn how to calculate and reduce the script’s runtime. A simple time command will help in calculating the execution time.PrerequisitesBesides having a terminal open, make sure you have the necessary scripts present in your...

read more

Lorem ipsum dolor sit amet consectetur


Submit a Comment

Your email address will not be published. Required fields are marked *

two × 3 =