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?

CamelBlues
  • 285
  • 1
  • 4
  • 12

3 Answers3

5

This is possible with command substitution.

DATEVAR=$(date +%s)
Rich Homolka
  • 31,057
  • 6
  • 55
  • 80
1
--[[z4us|binz--]]

export datevar=`date` # date embedded in backquotes

--[[z4us|binz--]]

echo $datevar

Lun 25 Gen 2016 15:56:14 CET
Nattgew
  • 1,133
  • 2
  • 12
  • 16
  • 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 09: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 09: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.

Daniel Liston
  • 356
  • 2
  • 7