Execute a command and put the results into a variable... all in a bash script [duplicate]
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?
This is possible with command substitution.
DATEVAR=$(date +%s)
--[[z4us|binz--]]
export datevar=`date` # date embedded in backquotes
--[[z4us|binz--]]
echo $datevar
Lun 25 Gen 2016 15:56:14 CET
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.