7

I create a variable and store the day, date & time in it:

NOW=$(date "+%a %d/%m/%Y% %H:%M")

Then I would like to pass $NOW to the mv command to rename a file.

e.g. Create file named a.txt with a title and the current date:

printf "File Report (" > ~/Desktop/a.txt
echo $NOW"):\n" >> ~/Desktop/a.txt  

Then I try to rename the file with the variable ($NOW) included in the name:

mv ~/Desktop/a.txt ~/Desktop/'File Report $NOW'.txt

What should that last line be? I also tried these two options.

mv ~/Desktop/a.txt ~/Desktop/'File Report' $NOW.txt

&

mv ~/Desktop/a.txt ~/Desktop/'File Report'${NOW}.txt
joshuatvernon
  • 1,530
  • 2
  • 23
  • 45

1 Answers1

9

Assuming a reasonably Bourne-like shell (such as bash), variable substitution does not happen inside single quotes. You need to use double quotes:

mv ~/Desktop/a.txt "${HOME}/Desktop/File Report ${NOW}.txt"

(I'm not sure whether the curly braces are required, but they can't hurt)

You will also need to change the date command to avoid the use of slashes. For example:

NOW="$(date '+%a %d-%m-%Y% %H:%M')"
Kevin
  • 28,963
  • 9
  • 62
  • 81
  • It is being saved within a bash script. I did that however it just doesn't rename the file at all. It stays as `a.txt`. I also tried `mv ~/Desktop/a.txt ~/Desktop/"File Report ${NOW}".txt` and that didn't rename the file either – joshuatvernon Jan 16 '16 at 03:58
  • 1
    There should be an error message in that case. Without the error message, I cannot help you. – Kevin Jan 16 '16 at 03:59
  • `mv: rename /Users/MyUser/Desktop/a.txt to ~/Desktop/File Report .txt: No such file or directory` I assume the ~ is not being unfolded and I would have to put in the exact directory in the double quotes – joshuatvernon Jan 16 '16 at 04:01
  • 1
    @joshuatvernon: Try it now. – Kevin Jan 16 '16 at 04:02
  • I'm now getting this error `My-MBP:Desktop me$ NOW=$(date "+%a %d/%m/%Y% %H:%M")` `My-MBP:Desktop me$ mv ~/Desktop/a.txt "${HOME}/Desktop/File Report ${NOW}.txt"` `mv: rename /Users/me/Desktop/a.txt to /Users/me/Desktop/File Report Sat 16/01/2016 15:08.txt: No such file or directory` – joshuatvernon Jan 16 '16 at 04:11
  • 1
    @joshuatvernon: Don't generate a date with slashes in it. You can't put those in a file name, and they cannot be escaped. – Kevin Jan 16 '16 at 04:12
  • It's okay I believe the issue is because OSX won't save a file with ":" in the name. – joshuatvernon Jan 16 '16 at 04:14
  • It worked once I changed the variable to not include "/" or ":". Thanks so much! – joshuatvernon Jan 16 '16 at 04:22
  • The end output was like this e.g. `NOW=$(date "+%a %d-%m-%Y% %Hh%Mm")` printed `Sat 16-01-2016 15h32m` – joshuatvernon Jan 16 '16 at 04:32