Putting functions in background

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Recursive functionHomeChapter 9 Challenges →
  • The & operator puts command in background and free up your terminal.
  • You can also put a function in background.

How Do I Put a Function In Background?

  • The syntax is as follows:
  echo "Do something"
  sleep 1

# put a function in the background
name &

# do something


  • You can display a series of dots (progress bar) while performing tape backup. This is useful for the user or operator to display a progress bar.
  • Create a shell script called progressdots.sh[1]:
# progressdots.sh - Display progress while making backup
# Based on idea presnted by nixCraft forum user rockdalinux
# Show progress dots
  echo -n "$0: Please wait..."
  while true
    echo -n "."
    sleep 5

    # put backup commands here
    tar -zcvf /dev/st0 /home >/dev/null 2>&1

# Start it in the background
progress &

# Save progress() PID
# You need to use the PID to kill the function

# Start backup
# Transfer control to dobackup()

# Kill progress
kill $MYSELF >/dev/null 2>&1

echo -n "...done."

Save and close the file. Run it as follows:

chmod +x progressdots.sh

Sample outputs:

./progressdots.sh: Please wait..................done.

External links

  • Bar is a simple tool to copy a stream of data and print a display for the user on stderr showing (a) the amount of data passed, (b) the throughput of the data transfer, and (c) the transfer time, or, if the total size of the data stream is known, the estimated time remaining, what percentage of the data transfer has been completed, and a progress bar.
  • pv (Pipe Viewer) is a terminal-based tool for monitoring the progress of data through a pipeline.
  • dialog - Another way to add a progress bar to your script using dialog --gauge.


← Recursive functionHomeChapter 9 Challenges →