Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers

up vote 4 down vote accepted

Use a function rather than a fixed variable:

#!/bin/bash

# Define a timestamp function
timestamp() {
  date +"%T"
}

# do something...
timestamp # print timestamp
# dp something else...
timestamp # print another timestamp
# continue...
share|improve this answer
2  
Depending on how you intend to use this, you'll still need to use command substitution: echo "$(timestamp): something happened". –  chepner Jun 12 at 13:16
 
Works perfect, Thanks. –  dan08 Jun 12 at 13:40

Use command substitution:

timestamp=$( date +%T )
share|improve this answer
 
This is what I already tried and it only prints out the time when the variable was initialized. –  dan08 Jun 12 at 13:09
1  
@dan08: That's how variables work. Use a function if you want dynamic output. –  choroba Jun 12 at 13:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.