Ubuntu: date command's time value note resolving properly in bash alias



Question:

I'm trying to set up a way for me to just type 'newjournal', and a new journal entry with a specific string of year-month-date-12hourclocktime.txt is created in a 'year' subdirectory in my 'journals' folder in 'documents', inside home folder.

I've got it set up as an alias using the following:

alias newjournal='nano /home/username/documents/journals/'$(date +%Y)'/'$(date +%F-%k%M).txt''  

So the year subfolder resolves correctly, and seemingly so does the first half of the date command. Tried appending the alias with sudo, didn't help.

Issue: For some reason, when I do this command the time value (%k) resolves to a few minutes ago...or maybe the last time nano ran this filename, maybe it's called an old buffer?
When I logoff it makes the correct file, then I save, wait a few minutes and try again, and it edits the old file instead of making a new one. Even if I remove the old file, it creates a new file with the old filename (incorrect time).

Here's a screenshot of what I'm trying to explain. Here I create a newjournal, save in nano within a second or two of executing the command, print the correct date/time, list the file that was created. Note the incorrect filename time (1249, as apposed to 13:11):

Can't embed pictures yet, so here's a link.

Anyways, it might be something simple, but I've tried different methods in the alias, such as putting double quotes around the whole thing and escaping properly, single quoting, escaping and spacing, etc.

Thanks for the read/help. Ubuntu 16.04 server.


Solution:1

The date commands are being evaluated at the time of alias declaration. I'll show you what I mean with an example alias t:

$ alias t="echo \"$(date +%k%M)\""  $ alias t  alias t='echo "1357"'  

You can fix this by using single quotes around the alias definition:

$ alias t='echo "$(date +%k%M)"'  $ alias t  alias t='echo "$(date +%k%M)"'  

For more info, see Difference between single and double quotes in Bash

Or if the command doesn't need to be a shell alias, use a function instead:

$ function t { echo "$(date +%k%M)"; }  $ declare -f t  t ()   {       echo "$(date +%k%M)"  }  

Update, per recent edit

$ alias t='echo '$(date +%k%M)''  $ alias t  alias t='echo 1400'  

Think of that alias definition as three strings:

  1. One single-quoted string: 'echo '
  2. One unquoted string: $(date +%k%M)
  3. One single-quoted null string: ''

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »