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

前端 未结 2 421
孤独总比滥情好
孤独总比滥情好 2021-01-06 07:23

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 subpro

相关标签:
2条回答
  • 2021-01-06 07:49

    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
    
    0 讨论(0)
  • 2021-01-06 07:59

    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
    
    0 讨论(0)
提交回复
热议问题