シェルのユーザー入力に基づいて日付/時刻を設定する

シェルのユーザー入力に基づいて日付/時刻を設定する

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")

おすすめ記事