Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to occasionally touch a file with the current timestamp as the filename. I would do so this way:

touch `date "+%Y-%m-%d_%H-%M"`.txt

However, I'd like to define an alias for this. When I try adding to the bashrc this:

alias td="touch `date \"+%Y-%m-%d_%H-%M\"`.txt"

the result is that the filename is the same during the entire session, since the `date ..` gets calculated just once during login...

How can I get the command to expand only when I call the alias? Or must I use a function for this?

Thanks

share|improve this question
up vote 4 down vote accepted

The shell expands the command line containing the alias command and passes something like td=touch 2010-09-17_21-54.txt to the alias command. You need to protect the special characters in the alias definition from expansion. The easiest way is to use single quotes instead of double quotes:

alias td='touch `date "+%Y-%m-%d_%H-%M"`.txt'

Then td is an alias for touch `date "+%Y-%m-%d_%H-%M"`.txt as desired.

Although it's not an issue here, I recommend using $(…) instead of `…`, so as to avoid difficulties with complex commands (backquotes have arcane and nonportable quoting rules, whereas dollar-parenthesis works intuitively):

alias td='touch $(date "+%Y-%m-%d_%H-%M").txt'
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .