Ubuntu – Date command not resolving properly in bash alias

aliasbashdatenano

I'm trying to set up a way for me to just type newjournal, and a new journal entry named year-month-date-time.txt is created in a year subdirectory in ~/documents/journals.

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):

screenshot

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.

EDIT: Here's the final alias that worked:

alias newjournal='nano /home/user/journals/"$(date +%Y)"/"$(date +%F-%H%M).txt"'

Needed to double quote the date commands inside the overall single-quoted alias.

Best Answer

The date commands are evaluated when you declare the alias.

Here's an example alias t:

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

You can fix this by using single quotes:

$ 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 an alias, use a function instead:

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

Or a script:

#!/bin/sh
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: ''
Related Question