Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

Show date and time at shell prompt

SOLVED
Go to Solution
Advisor

Show date and time at shell prompt

Currently, i set my prompt as the following.
===========================
export DATE="$(date '+%d%b')"
export SECONDS="$(date '+3600*%H+60*%M+%S')"
typeset -Z2 _h; typeset -Z2 _m ; typeset -Z2 _s # 2 digits, zero padded
# hours, minutes and seconds...
_hh="(SECONDS/3600)%24"
_mm="(SECONDS/60)%60"
_ss="(SECONDS)%60"
_time='${_x[(_m=_mm)==(_h=_hh)==(_s=_ss)]}$_h:$_m:$_s'
export PS1=$(echo "${DATE}${_time} `whoami`@`hostname`
\$PWD
# ")
======================================

It works fine in sh
07Apr18:53:48 root@sa27
/
# ps
PID TTY TIME COMMAND
22757 pts/1 0:00 ps
6257 pts/1 0:00 sh

However, when i change to ksh, it doesnt work anymore.

07Apr19:00:30 root@sa27
/
# ksh
07Apr${_x[(_m=_mm)==(_h=_hh)==(_s=_ss)]}$_h:$_m:$_s root@umwsa27
$PWD
#

Anyone can show where the problem is?
Thanks.
Nash
4 REPLIES
Highlighted
Honored Contributor Honored Contributor

Re: Show date and time at shell prompt

# set +u

will change to time.

Easy to suggest when don't know about the problem!
Acclaimed Contributor Acclaimed Contributor

Re: Show date and time at shell prompt

Hi Nash:

The use of SECONDS as a variable to which you make assignments is not sane. Have a look at the 'sh-poxix' and/or 'ksh' manpages. In particular: "Each time this parameter is referenced, the number of seconds since shell invocation is returned. If this parameter is assigned a value, the value returned upon reference is the value that was assigned plus the number of seconds since the assignment." Should you "insist" on using that name, at least 'unset' SECONDS beforehand.

Regards!

...JRF...
Advisor

Re: Show date and time at shell prompt

Thank you all for the solution and advice.
Nash
Respected Contributor Respected Contributor

Re: Show date and time at shell prompt

Hi

The problem of dealing the unset variables is solved by

set +u

But it is not necessary because shell supports some facilities in parameter substitution to deal the unset variables:

set -u
echo ">>${A}<<"
ksh: A: parameter not set
echo ">>${A:-}<<" # prints nothing
>><<

Therefore, if you change the line where variable _time is initalize as suggested:

_time='${_x[(_m=_mm)==(_h=_hh)==(_s=_ss)]:-}$_h:$_m:$_s'

then you won't be concerned with the setting 'set +u'