Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm working on a bash script that backs up a configuration file before copying over a new file.

Here's what my snippet looks like:

mv ~/myStuff.conf  ~/myStuff.conf.bak
cp ~/new/myStuff.conf ~/myStuff.conf

Every time this script is run, I'd like there the backup to have a unix timestamp in the filename. I tried this

DATEVAR=date +%s
mv ~/myStuff.conf  ~/myStuff.conf.$DATEVAR.bak

But this doesn't work, since the date function doesn't execute and bash sees it as a string, and the resulting file ends up being

myStuff.conf.date+%s.bak

Any ideas on how to get the results of the date function into a variable?

share|improve this question
    
up vote 4 down vote accepted

This is possible with command substitution.

DATEVAR=$(date +%s)
share|improve this answer
--[[z4us|binz--]]

export datevar=`date` # date embedded in backquotes

--[[z4us|binz--]]

echo $datevar

Lun 25 Gen 2016 15:56:14 CET
share|improve this answer
    
Besides correctly formatting for code, an explanation of what is going on would improve this answer. – Nattgew Jan 25 at 15:51
    
Well, Nattgew FYI: export makes the variable available in the environment to be used in next steps. Backquotes surround a bash-command that will be executed. I thought superusers are supposed to know these basics, but of course we have to think of readers who arrive here via any search engine :-) – Klaas-Z4us-V Jan 26 at 9:40
    
For bash you may read any shell and I used the command without parameters to see what is the default. – Klaas-Z4us-V Jan 26 at 9:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .