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
Best Answer
The shell expands the command line containing the
alias
command and passes something liketd=touch 2010-09-17_21-54.txt
to thealias
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:Then
td
is an alias fortouch `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):