Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a timer in Bash Scripting?

Tags:

bash

timestamp

Good day! Is there any way to include a timer (timestamp?or whatever term it is) in a script using bash? Like for instance; every 60 seconds, a specific function checks if the internet is down, if it is, then it connects to the wifi device instead and vice versa. In short, the program checks the internet connection from time to time.

Any suggestions/answers will be much appreciated. =)

like image 648
Suezy Avatar asked Aug 04 '09 07:08

Suezy


People also ask

How do I show time in a bash script?

To get current date and time in Bash script, use date command. date command returns current date and time with the current timezone set in the system.

How do you display time in Shell?

Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...

What is bash time command?

time command in Linux is used to execute a command and prints a summary of real-time, user CPU time and system CPU time spent by executing a command when it terminates.

How do I delay in bash?

It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number. Consider this basic example: echo "Hello there!" sleep 2 echo "Oops!


2 Answers

Blunt version

while sleep 60; do
  if ! check_internet; then
    if is_wifi; then
       set_wired
    else
       set_wifi
    fi
  fi
done

Using the sleep itself as loop condition allows you to break out of the loop by killing the sleep (i.e. if it's a foreground process, ctrl-c will do).

If we're talking minutes or hours intervals, cron will probably do a better job, as Montecristo pointed out.

like image 72
falstro Avatar answered Sep 22 '22 02:09

falstro


You may want to do a man cron.

Or if you just have to stick to bash just put the function call inside a loop and sleep 60 inside the iteration.

like image 44
Alberto Zaccagni Avatar answered Sep 21 '22 02:09

Alberto Zaccagni