recover date from bash ubuntu

3

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

Does anyone know how to do this?

Code sample:

    #!/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
    
asked by anonymous 13.09.2018 / 19:44

1 answer

4

In the same way that you used %d-%m-%Y , just use %H-%M-%S

General solution in Bash, if you want to save 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 sorting, the ideal is the most significant first

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

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


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

  

link

    
13.09.2018 / 19:49