Serge
Serge

Reputation: 741

BASHRC PS1 show datetime but plus 3 hours

Every of us set own convenience working with Linux shell, for example I use /root/.bashrc

PS1='[\h:\w] \D{%F %T}\n\$ '

to show servername + current server datetime + newline for command - so it looks like

[servername217:~] 2022-02-06 00:55:02
#

But I met a stumbling block with syntax trying to set not server time, but my home, for example plus 3 hours. It's easy to make with regular BASH

date -d '+ 3 hour' '+%F %T'

but when I try to use, for example,

PS1='[\h:\w] [date -d '+ 3 hour' '+%F %T']\n\$ '

I always get an error. It seems PS1 understands only

\D{%F %T}

but how to add 3 hours to %T under this format ? Or there is an another way ?

Upvotes: 0

Views: 213

Answers (3)

dan
dan

Reputation: 5231

For bash v4.2 or higher, you can use the printf date format specifier. This should be more efficient than forking a new date(1) process at each prompt:

PS1='[\h:\w] $(printf "%(%F %T)T" "$((\D{%s} + 60*60*3))")\n\$ '

Personally, instead of a command substitution in PS1, I prefer to set a variable with PROMPT_COMMAND (a string which executed before each prompt), and use that in PS1. This makes it easy for example to unset PROMPT_COMMAND if the command is causing trouble.

That can be done like this (bash 4.3 or higher required for printf "%(%s)T" to print the current date):

PROMPT_COMMAND='
ps1_date=$(printf "%(%F %T)T" \
"$(($(printf "%(%s)T") + 60*60*3))"
)'

Or this (bash 4.4 or higher required for ${ps1_date@P}):

PROMPT_COMMAND='
    ps1_date="\D{%s}"
    ps1_date=${ps1_date@P}
    ps1_date=$(printf "%(%F %T)T" "$((ps1_date+60*60*3))")'

Then just use that variable here:

PS1='[\h:\w] ${ps1_date}n\$ '

Upvotes: 2

pynexj
pynexj

Reputation: 20688

It's a bit too heavyweight to use the external date command. If you have Bash 4.3+ you can use the builtin printf %(fmt)T:

$ cat ps1
NOW_PLUS_3_HOURS=''

function _prompt_command()
{
    local secs

    printf -v secs '%(%s)T'
    (( secs += 3 * 3600 ))
    printf -v NOW_PLUS_3_HOURS '%(%F %T)T' $secs
}

PROMPT_COMMAND=_prompt_command
PS1='[$NOW_PLUS_3_HOURS] $ '
$ date +'%F %T'
2022-02-06 16:37:02
$ source ./ps1
[2022-02-06 19:37:06] $
[2022-02-06 19:37:11] $

And by using the PROMPT_COMMAND you can do a lot more interesting things.

Upvotes: 2

Cyrus
Cyrus

Reputation: 88583

This might help:

PS1="[\h:\w] \$(date -d '+ 3 hour' '+%F %T')\n\$ "

Upvotes: 2

Related Questions