根据 shell 中的用户输入设置日期时间

根据 shell 中的用户输入设置日期时间

我正在创建脚本来检查 RTC 工作,为此,我首先从用户输入的yyyy mm dd hh:mm:ss格式中获取日期和时间。

read -p "Enter the date:" val
echo $val
date -s "${val}"

现在我收到错误:

date: invalid date ‘2016 01 22 14:00

请帮忙。提前致谢。

答案1

联机帮助页:

DATE STRING
       The --date=STRING is a mostly free format human readable date string such as "Sun, 29 Feb 2004 16:21:42 -0800"
       or  "2004-02-29  16:21:42" or even "next Thursday".  A date string may contain items indicating calendar date,
       time of day, time zone, day of week, relative time, relative date, and numbers.  An empty string indicates the
       beginning  of  the  day.   The  date string format is more complex than is easily documented here but is fully
       described in the info documentation.

因此,yy-dd-mm hh:mm:ss应首选甲酸盐作为输入date -s

请尝试以下操作:

(unset -v IFS # restore IFS to default
read -p "Enter the date:" y m d time rest_ignored
date -s "$y-$m-$d $time")

相关内容