Com treballar amb la data i l'hora a Bash mitjançant l'ordre de data


L'ordre de data és un programa bash extern que permet configurar o mostrar la data i l'hora del sistema. També ofereix diverses opcions de format. L'ordre de data s'instal·la per defecte a totes les distribucions de Linux.

$ which date
$ type -a date

Escriviu l'ordre de data al terminal que mostrarà la data i l'hora actuals.

$ date

Amb l'ordre de data, la data del sistema, l'hora i la zona horària es poden modificar i el canvi s'ha de sincronitzar amb el rellotge del maquinari.

$ date --set="Thu Nov 12 13:06:59 IST 2020"
$ hwclock --systohc

Un bon lloc per obtenir la llista d'opcions de format serà la pàgina de manual.

$ man date

Vegem algunes de les opcions de format més habituals que utilitzarem.

  • Per aplicar el format, utilitzeu + seguit de formatador.
  • Per obtenir una llista d'opcions de format per a GNU\LINUX, mireu la pàgina de manual enllaçada.
  • Per obtenir una llista d'opcions de format per a BSD, mireu la pàgina de manual enllaçada.

Les dues parts importants de l'ordre de data és utilitzar l'opció Format +% i –date.

Ara apliquem una mica de format a l'ordre de data. Per aplicar el format, afegiu el signe més (+) seguit de %formatter com es mostra als exemples.

Fem una ullada a com utilitzar formatadors relacionats amb la data en un script de shell senzill anomenat date.sh.

# PRINT YEAR,MONTH,DAY AND DATE...

echo "We are in the year = $(date +%Y)"
echo "We are in the year = $(date +%y)"

# Difference between %Y and %y is %Y will print 4 digits while %y will print the last 2 digits of the year.

echo "We are in the month = $(date +%m)"
echo "We are in the month = $(date +%b)"
echo "We are in the month = $(date +%B)"

# Difference between %B and %b is, %B will print full month name while %b will print abbreviated month name.

echo "Current Day of the month = $(date +%d)"

echo "Current Day of the week = $(date +%A)"
echo "Current Day of the week = $(date +%a)"

# Difference between %A and %a is, %A will print full Weekday name while %a will print abbreviated weekday name.

# Instead of formatting to get the date, we can use %D which will print the date as %m/%d/%y or %F which prints in %Y-%M-%d format.

echo "Date using %D = $(date +%D)"
echo "Date using %F = $(date +%F)"

Fem una ullada a com utilitzar formatadors relacionats amb el temps en un script de shell senzill anomenat time.sh.

# PRINT HOURS, MINS, SECONDS, NANO SECONDS

echo Hours = $(date +%H)
echo Minutes = $(date +%M)
echo Seconds = $(date +%S)
echo Nanoseconds = $(date +%N)
echo Epoch Time = $(date +%s)

echo "current time = $(date +%H:%M:%S:%N)"

# can also use %T which displays Time in HH:MM:SS format.

echo "current time in 24 hour format = $(date +%T)"

# can also use %r to display time in 12 hour format.

echo "current time in 12 hour format = $(date +%r)"

Amb --date o -d l'entrada del senyalador es pot passar com a cadena i l'ordre de data sap gestionar-ho de manera intel·ligent.

Vegem alguns exemples per entendre com funciona.

# Print yesterday's date and time.
echo "Yesterday = $(date -d "Yesterday")"

# Print Tomorrow date and time.
echo "tomorrow = $(date -d "tomorrow")"

# Find what is the date and time before 10 days from now.
echo "Before 10 days = $(date -d "tomorrow -10 days")"

# Find last month and next month
echo "Last month = $(date -d "last month" "%B")"
echo "Next month = $(date -d "next month" "%B")"

# Find last year and next year
echo "Last Year = $(date -d "last year" "+%Y")"
echo "Next Year = $(date -d "next year" "+%Y")"

# Forecast the weekday
echo "2 days away from today and it comes on weekdays? = $(date -d "Today +2 days" "+%A")

calcula el nombre de dies entre 2 dates donades.

$ echo $(( ( $(date -d "2020-11-10" "+%s") - $(date -d "2020-11-01" "+%s") ) / 86400))

Trobeu que l'any donat sigui un any de traspàs o no.

$ for y in {2000..2020}; do date -d $y-02-29 &>/dev/null && echo $y is leap year; done

Assignació de la sortida de l'ordre de data a una variable.

$ TODAY=$(date +%Y-%m-%d)
OR
$ TODAY1=$(date +%F)
$ echo $TODAY 
$ echo $TODAY1

Creeu fitxers de registre amb la data afegida al nom del fitxer.

Afegir data i hora mentre es creen fitxers de registre, còpies de seguretat o fitxers de text és una operació habitual que ens trobarem amb més freqüència. Posem un exemple, per fer una còpia de seguretat, hem creat un script de shell.

Aquest script farà una còpia de seguretat de les 00:00 a les 23:59 i està programada per executar-se diàriament a les 00:00 del dia següent. Volem crear fitxers de registre amb el format de data d'ahir.

CUSTOM_FORMAT=$(date --date "Yesterday" "+%d-%y-%H:%M")
LOG_FILE=/var/log/custom_application/application_${CUSTOM_FORMAT}.log
echo "Script started" >>  ${LOG_FILE}
...
CODE BLOCKS
...
echo "Script completed" >> ${LOG_FILE}

Això és tot per aquest article. En aquest article, hem vist com utilitzar la data i l'hora de bash a Linux. Feu-nos saber els vostres comentaris.