date
信頼できる秒を使用するだけです:
ご指摘のとおり、英語の時間演算に依存している場合、基礎となる計算に関する詳細の多くが隠されています。たとえば-d yesterday
、 と-d 1 day ago
は異なる動作をします。
代わりに、UNIXエポックUTCからの(正確に文書化された)秒に確実に依存し、算術演算を実行して必要な瞬間を取得できます。
date -d @$(( $(date +"%s") - 24*3600)) +"%Y-%m-%d"
これは別の回答で指摘されました。この形式は、さまざまなコマンド ライン フラグを使用するプラットフォーム間で移植性が高くdate
、言語に依存せず (たとえば、フランス語のロケールでは「yesterday」と「hier」)、率直に言って (長期的には) 覚えやすくなります。すでに知っています。そうでなければ、あなたは自問し続けるかもしれませ-d 2 hours ago
ん-d 2 hour ago
: または「それは私が欲しいですか?」)-d yesterday
。-d 1 day ago
ここでの唯一の注意点は、@
.
bashだけで武装:
bash のみで bash を実行すると、printf ビルトインを使用して昨日の時刻を取得することもできます。
%(datefmt)T
causes printf to output the date-time string resulting from using
datefmt as a format string for strftime(3). The corresponding argu‐
ment is an integer representing the number of seconds since the
epoch. Two special argument values may be used: -1 represents the
current time, and -2 represents the time the shell was invoked.
If no argument is specified, conversion behaves as if -1 had
been given.
This is an exception to the usual printf behavior.
そう、
# inner printf gets you the current unix time in seconds
# outer printf spits it out according to the format
printf "%(%Y-%m-%d)T\n" $(( $(printf "%(%s)T" -1) - 24*3600 ))
または、同等に一時変数を使用します(外側のサブシェルはオプションですが、環境変数をクリーンに保ちます)。
(
now=$(printf "%(%s)T" -1);
printf "%(%Y-%m-%d)T\n" $((now - 24*3600));
)
注:%()T
フォーマッタへの引数はデフォルトを想定しないとマンページに記載されています-1
が、代わりに 0 を取得しているようです(ありがとう、bashマニュアルバージョン4.3.48)