Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

1 Answer 1

up vote 2 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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.