Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create timestamp variable in bash script

I am trying to create a timestamp variable in a shell script to make the logging a little easier. I want to create the variable at the beginning of the script and have it print out the current time whenever I issue echo $timestamp. It proving to be more difficult then I thought. Here are some things I've tried:

timestamp="(date +"%T")" echo prints out (date +"%T")

timestamp="$(date +"%T")" echo prints the time when the variable was initialized.

Other things I've tried are just slight variations that didn't work any better. Does anyone know how to accomplish what I'm trying to do?

like image 834
Dan Avatar asked Jun 12 '13 13:06

Dan


People also ask

How do you add a timestamp to a script?

Ctrl / Cmd + : to insert date: 7/21/2020. Ctrl / Cmd + Shift + : to insert time: 3:25:24 PM. Ctrl / Cmd + Alt + Shift + : to insert the full timestamp: 7/21/2020 12:05:46.

What is $() in bash script?

$() Command Substitution According to the official GNU Bash Reference manual: “Command substitution allows the output of a command to replace the command itself.

How do I declare a variable in bash?

A variable in bash is created by assigning a value to its reference. Although the built-in declare statement does not need to be used to explicitly declare a variable in bash, the command is often employed for more advanced variable management tasks.


1 Answers

If you want to get unix timestamp, then you need to use:

timestamp=$(date +%s) 

%T will give you just the time; same as %H:%M:%S (via http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/)

like image 178
dchakarov Avatar answered Sep 22 '22 18:09

dchakarov