Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the current date in bash without spawning a sub-process

This question is pure curiosity. It is easy to get a date by running the date command from bash, but it is an external executable and requires spawning a subprocess. I wondered whether it is possible to get the current time/date formatted without a subprocess. I could only find references to date/time formats in the context of PS1 and HISTTIMEFORMAT. The latter allows this:

HISTTIMEFORMAT="%Y-%m-%d_%H:%M:%S "
history -s echo
x=$(history)
set -- $x
date="$2"

This comes close, but the $(history) spawns a subprocess, as far as I can tell.

Can we do better?

like image 886
Harald Avatar asked Mar 25 '16 16:03

Harald


People also ask

How do I get current date in bash?

To get current date and time in Bash script, use date command. date command returns current date and time with the current timezone set in the system.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


2 Answers

bash 4.2 introduced a new specifier for printf; this was extended in bash 4.3 to use the current time if no argument is given. %()T expands to the current time, using the format appearing inside the parentheses.

$ printf '%(%Y-%m-%d_%H:%M:%S)T\n'
2016-03-25_12:38:10
like image 126
chepner Avatar answered Nov 15 '22 03:11

chepner


With Linux and GNU bash 4:

#!/bin/bash

while IFS=: read -r a b; do 
  [[ $a =~ rtc_time ]] && t="${b// /}"
  [[ $a =~ rtc_date ]] && d="${b// /}"
done < /proc/driver/rtc

echo "$d $t"

Output:

2016-03-26 08:03:09
like image 43
Cyrus Avatar answered Nov 15 '22 04:11

Cyrus