0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Linux の date コマンドのデフォルトフォーマットを変更する

Last updated at Posted at 2023-11-21

デフォルトのフォーマットを指定する方法

次のように date コマンドの引数を調整する関数 date_with_default_format を定義し、date のエイリアスとします。date_with_default_format は引数でフォーマットが指定されなかった場合、引数にデフォルトのフォーマットを追加します。その後、date コマンドを呼び出します。

.bashrc
function date_with_default_format
{
    # フォーマットが指定されなかった場合のデフォルト.
    declare -r default_format='+%F %T %Z'

    # フォーマットが指定された場合に true.
    declare format_specified=false

    declare option

    # 引数でフォーマットが指定されているかどうか判定する.
    for option in "$@"
    do  
        if [[ "${option}" == +* ]]; then
            format_specified=true
        fi
    done

    # フォーマットが指定されなかった場合は, 引数にデフォルトのフォーマットを追加する.
    if ! ${format_specified}; then
        set -- "$@" "${default_format}"
    fi

    date "$@"
}
alias date=date_with_default_format

ロケールに依存したデフォルトフォーマットにする場合

Linux の date コマンドは環境変数 LC_TIME ロケールカテゴリに応じたフォーマットで出力します。ロケールに依存したデフォルトフォーマットにしたい場合は、それらの環境変数を設定します。

$ LC_TIME=en_US.UTF-8 date
Tue Nov 21 12:45:20 JST 2023

$ LC_TIME=ja_JP.UTF-8 date
火 11 21 12:45:20 JST 2023

$ LANG=ja_JP.UTF-8 date
火 11 21 12:45:20 JST 2023

関連情報

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?