Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Linux by (18.4k points)

I am trying to build a timestamp variable in a shell script to perform the logging slight easier. I am trying to build the variable at every beginning of the script and have it print out this current time whenever I issue echo $timestamp. It is difficult than I thought. These are the things I've tried:

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

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

I also tried are just slight changes that didn't work. I need help.

1 Answer

0 votes
by (36.8k points)

To work on the current timestamp and not the time when your fixed variable is defined, this trick is to use the function and not the variable:

#!/bin/bash

# Define a timestamp function

timestamp() {

  date +"%T" # current time

}

# do something...

timestamp # print timestamp

# do something else...

timestamp # print another timestamp

# continue...

If you don't like this format given by the %T specifier you can combine the other time conversion specifiers accepted through date. For the GNU date, you can find the list of the official documentation here

Want to be a Linux expert? Come and join this Linux course

Do check out the video below

Related questions

0 votes
1 answer
asked Feb 4, 2021 in Linux by blackindya (18.4k points)
0 votes
1 answer
0 votes
1 answer
asked Dec 10, 2020 in Linux by blackindya (18.4k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...