Bash alias create file with current timestamp in f

2020-03-03 05:35发布

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?

2条回答
成全新的幸福
2楼-- · 2020-03-03 06:10

$ 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
查看更多
不美不萌又怎样
3楼-- · 2020-03-03 06: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.

查看更多
登录 后发表回答