1

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?

marked as duplicate by nc4pk, DavidPostill, mdpc, G-Man, Pimp Juice IT Feb 27 '17 at 19:55

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Technically, that other one is a duplicate of this as this is 3 years older. – music2myear Feb 24 '17 at 23:57
5

This is possible with command substitution.

DATEVAR=$(date +%s)
1
--[[z4us|binz--]]

export datevar=`date` # date embedded in backquotes

--[[z4us|binz--]]

echo $datevar

Lun 25 Gen 2016 15:56:14 CET
  • Besides correctly formatting for code, an explanation of what is going on would improve this answer. – Nattgew Jan 25 '16 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 '16 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 '16 at 9:49
1

This does not answer the variable holding the output of a command. That is already answered. As for the rest of your example script;

A little shorter version:

mv ~/myStuff.conf  ~/myStuff.conf.$(date +%s)

No need to set a variable for something you only need or use once. Also, to be compatible with more shells, you could also use this syntax:

mv ~/myStuff.conf  ~/myStuff.conf.`date +%s`

It just seems to me that having the datestamp as an extension eliminates the need for the additional .bak in the filename.

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