Magazine

Running Functions in the Background in Linux Bash Script

Posted on the 28 April 2021 by Satish Kumar @satish_kumar86

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

This should produce the following output:

Output:

Task...done.Started backupCompleted backup

Command source and period (.)

Normally, whenever weentera command, the new process gets created. If we want to make functions from the script to be made available inthecurrent 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 thesourceor.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 functions.sh

Or you could use this:

$ . 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 you could enter the following:

$ ./path/to/functions.sh 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.


Back to Featured Articles on Logo Paperblog