How to escape commands in a bashrc alias?

7

2

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

GJ.

Posted 2010-09-17T21:30:44.507

Reputation: 8 151

Answers

7

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'

Gilles 'SO- stop being evil'

Posted 2010-09-17T21:30:44.507

Reputation: 58 319

0

The accepted answer is perfect almost always. For those times when you MUST use double-quotes instead of single-quotes, the following works:

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

John Ward

Posted 2010-09-17T21:30:44.507

Reputation: 21