bashシェルスクリプトで$(date)
を使ってみましたが、日付をYYYY-MM-DD形式で表示したいのです。どうすればいいのでしょうか?
bash (>=4.2) では、外部の date
(通常は GNU date) ではなく、 printf の内蔵日付フォーマッタ (bash の一部) を使用することが望ましいです。
このように
# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1
# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1
# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal
bash (<4.2)では。
# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')
# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')
# print current date directly
echo $(date '+%Y-%m-%d')
その他の日付フォーマットについては、date man pages (bash以外の外部コマンド)を参照してください。
man date