Running functions in the background in Linux bash script

April 28, 2021

Comments

Adsense

Adsense

Adsense

Adsense

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 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 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.

Satish Kumar

Satish Kumar

I am Satish Kumar, Founder of LinuxConcept. Linux and F.O.S.S enthusiast, love to work on open source platform and technologies.

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Related Posts

Backup of files in Linux using command line

In IT or our day-to-day computer industry activities, taking backup is one of the most important activities. Previously, offices were required to keep important paper in a safe place; but if a fire breaks out, then everything is finished. In the digital world, taking...

Using awk in Linux

awk is a program that has its own programming language for performing data-processing and generating reports. The GNU version of awk is gawk. awk processes data, which can be received from a standard input, input file, or as the output of any other command or process....

0 Comments

0 Comments

Submit a Comment

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

2 × two =

News & Updates

Join Our Newsletter

Adsense

Adsense

Adsense

Adsense