Wednesday, February 24, 2016

To run a command repeatedly in Linux

For many cases, we need to execute the command repeatedly in the shell. We can do it by cron. But in that cat its not feasible to use cron if the interval time is less than 1 min or more. Suppose, we are inclined to get the output like the top command for a specific command. We can do that in the following ways as:
watch Command
# watch free -m [By Default 2 Sec Interval]
# watch -n 10 script.sh [For the interval of 10 Seconds]
Sleep Command:
a) inside For Loop
# for i in {1..10}; do echo -n "This is a test in loop $i "; date ; sleep
b) Inside while Loop
# while true; do echo -n "This is a test of while loop";date ; sleep 5; done




Watch Command:
Watch is a Linux command to execute a command periodically asn shows the output in the screen.

# watch free -m
The above command execute the free -m command repeatedly with the interval of 2 seconds in default. In case of changing the default interval period we can execute the command as:
# watch -n 10 script.sh
in that case, the above query will return with the out for each 10 second of interval.

other useful options of watch command:

-b : creates the beep sound, if the exit of the
-c: Interprets the ANSI color of the sequence
-d : highlight teh changes in the command output

we can monitor the progress of the copy command by checking the disk usage[du command] of the newly copied file at the time of copying as:
# watch -n 0.1 du -s /home/tecmint/ubuntu-15.10-desktop-amd64.iso 
Sleep Command:

We can use sleep command inside a loop as the interval period to execute the desired command or script repeatedly as:

inside For Loop:
# for i in {1..10}; do echo -n "This is a test in loop $i "; date ; sleep
inside While loop:
# while true; do echo -n "This is a test of while loop";date ; sleep 5; done



No comments: