retrieve date from bash Ubuntu

Asked

Viewed 49 times

3

I am mounting a scrip to dump a Mysql server, the name of the generated file is like this (bckp_all_13-09-2018.tar.bz2), but I wanted to store the time too, so (bckp_all_13-09-2018_14:44:22.tar.bz2).

Someone knows how to do it?

Example of the Code:

    #!/bin/bash
MY_USER="root"
MY_PASSWORD="123456"
MY_HOME="/home/hugo"
case $1 in
"backupall")
    cd $MY_HOME/Backup
    mysqldump --opt --password=$MY_PASSWORD --user=$MY_USER  --all-databases > bckp_all_$(date +'%d-%m-%Y').sql
    tar -cvjf bckp_all_$(date +'%d-%m-%Y').tar.bz2 bckp_all_$(date +'%d-%m-%Y').sql
    rm bckp_all_$(date +'%d-%m-%Y').sql;;
*)  echo "Others";;
esac
  • 2

    '%d-%m-%Y' sets the output format, then just add the parameters of hours, minutes and seconds.

1 answer

4


The same way you used to %d-%m-%Y, just use %H-%M-%S

General solution in Bash, if you want to store in variable instead of repeating the 3x command:

BKP_NAME=$(date -u +%Y-%m-%d_%H-%M-%S_UTC)

Local time:

BKP_NAME=$(date +%Y-%m-%d_%H-%M-%S_%z)
  • Note that %d %m %Y is bad for ordering, the ideal is the most significant first.

  • Avoid the :, they have special meaning in file path. If you really want to use tabs, use 14h30m18 is reasonable for hours.

  • I recommend using the -u, to avoid confusion with daylight savings (and as in the example, note that it is UTC in the file name). This way you will have universal time (you can even use the location, except -u, but you will have to be careful with daylight savings time and portability of the script to other machines). In the case of the local example above, I used the %z at the end, to add the spindle.


For other parameters, see man date via command line or online:

https://linux.die.net/man/1/date

  • It worked, but the time is wrong. It is not in the zone of sao paulo.

  • -u is UTC, just to avoid fuso problem (if you use zone, you will need to note one more parameter, the offset, otherwise summer time will make a mess). But if you want to be paul, just take the -u and configure the right server.

  • Very good, thank you for your help.

  • 1

    @Hugoborges I edited with an example with time zone at the end. Ex: 2017-12-20_13-49-12_-0300 (-0300 is the time zone of Brasilia in normal time, in summer time will stay -0200)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.