Putting functions in background
From Linux Shell Scripting Tutorial - A Beginner's handbook
- The & operator puts command in background and free up your terminal.
- You can also put a function in background.
Contents |
How Do I Put a Function In Background?
- The syntax is as follows:
name(){
echo "Do something"
sleep 1
}
# put a function in the background
name &
# do something
Example
- 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]:
#!/bin/bash # progressdots.sh - Display progress while making backup # Based on idea presnted by nixCraft forum user rockdalinux # Show progress dots progress(){ echo -n "$0: Please wait..." while true do echo -n "." sleep 5 done } dobackup(){ # 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 MYSELF=$! # Start backup # Transfer control to dobackup() dobackup # Kill progress kill $MYSELF >/dev/null 2>&1 echo -n "...done." echo
Save and close the file. Run it as follows:
chmod +x progressdots.sh ./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.
References
- ↑ Shell Script To Show Progress Indicators / Dots While Making The Backups from the nixCraft forum.