shell 输出Unix时间戳
秒级时间戳:
$ echo $(date +%s)
1681983716
毫秒/微秒/纳秒 时间戳:
$ echo $(($(date +%s%N)/1000000))
1681984600895
$ echo $(($(date +%s%N)/1000))
1681984779486536
$ date +%s%N
1681984840382296459
可以把命令保存到一个shell脚本中方便后续使用
#!/usr/bin/env bashshow_help() {cat <<EOT
Usage:timestamp [options]Show current unix timestamp, the duration since 1970-01-01 00:00:00 UTC, default in secondsOptions:-s Timestamp in seconds-m, --ms Timestamp in milliseconds-u, --us Timestamp in microseconds-n, --ns Timestamp in nanoseconds
EOT
}if [ $# -lt 1 ]; thendate +%sexit 0
ficase $1 in
-s)date +%s;;
-m|--ms)echo $(($(date +%s%N)/1000000));;
-u|--us)echo $(($(date +%s%N)/1000));;
-n|--ns)date +%s%N;;
*)printf "invalid option: %s\\n" "$1" >&2show_helpexit 1;;
esac
Example:
$ chmod +x timestamp.sh
$ ./timestamp.sh
1681988240
$ ./timestamp.sh -m
1681988247134
$ ./timestamp.sh --us
1681988251839104
$ ./timestamp.sh --ns
1681988254563233455