Question on storing a variable from a rename action.

I have a simple if statement I am working with to validate if a file exist and rename it using the following method:

if [ -a ".htaccess" ];then mv .htaccess .htaccess.bak_$(date +%F-%T);fi;

The output is just as it should be and I need to have that saved as a variable so that I can implement a revert changes option calling a $var that would equate to the .htaccess.bak_2015-05-04-18:49:13 generated and renaming it back. I realize I could easily make a command that reverts the changes finding the file using regular expressions although that seems dodgy as even if the likelihood of encountering a file named similarly is low it is possible.

My understanding of storing and calling variables is still pretty basic and I gladly welcome any help for a solution and understanding of a save in this manner.

p.s also counts as intro thread. Hello!

simply assign it as a variable first with var= and recall it later as $var . remember, you should almost always quote anything that has a $ in it!

if [ -a .htaccess ]; then
  htaccess_bak=".htaccess.bak_$(date +%F-%T)"
  mv .htaccess "$htaccess_bak"
fi
...
if [ -n "$htaccess_bak" ]; then # check if this variable is not empty
  mv "$htaccess_bak" .htaccess
fi
1 Like

Thank you neutronscott, That works perfect!

That works if used in the same shell / script. Once you leave either, the var would be lost, and you need to recreate the file name and better do a -a check again.