8

I am trying to create a bash alias that will print the current UNIX timestamp every time the alias is called. I have the following in my bash profile:

alias unix="echo "$(date +%s)""

However, it seems that the current unix timestamp is being stored as soon as the bash profile is sourced, and it doesn't change each time the alias is called.

For example, if I call the unix alias three times 10 seconds apart, the output is always the same. How can I create an alias that will evaluate the unix timestamp at the time the alias is called. Is this possible?

flyingL123
  • 7,686
  • 11
  • 66
  • 135
  • Possible duplicate of [Append date to filename in linux](https://stackoverflow.com/q/1795678/608639), [Appending a current date from a variable to a filename](https://unix.stackexchange.com/q/57590), [Adding timestamp to a filename with mv in BASH](https://stackoverflow.com/q/8228047/608639), etc. – jww Oct 15 '19 at 08:24

2 Answers2

13

Use single quotes to prevent immediate expansion.

alias unix='echo $(date +%s)'

Update: While I'm happy to have been able to explain the different expansion behavior between single and double quotes, please also see the other answer, by Robby Cornelissen, for a more efficient way to get the same result. The echo is unnecessary here since it only outputs what date already would output by itself. Therefore, date doesn't need to be run in a subshell.

Ivan X
  • 2,165
  • 16
  • 25
  • Worked great thanks. It won't let me accept your answer for another 7 minutes, but I will. – flyingL123 Jun 16 '14 at 03:48
  • Also, just for giggles, you could accomplish same with double quotes by escaping the $, which would also prevent immediate expansion: `alias unix="echo \$(date +%s)"`. – Ivan X Jun 16 '14 at 04:10
  • I could -1 for superfluous use of "echo", but I won't. :) – aqn Jun 17 '14 at 04:12
  • Well, thanks for that. I was trying to explain why the asker's answer wasn't working, but I agree that it's not the most efficient way of getting the result. You could upvote the other, non-echo, answer below ;) – Ivan X Jun 17 '14 at 13:12
4

$ alias unix="date +%s"
$ touch myfile.$(unix)
$ touch myfile.$(unix)
$ ls -l myfile*
-rw-r--r--  1 rbednark  wheel  0 Apr 11 21:46 myfile.1460436366
-rw-r--r--  1 rbednark  wheel  0 Apr 11 21:46 myfile.1460436368
Rob Bednark
  • 25,981
  • 23
  • 80
  • 125
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156