Question

I am trying to display the date of execution of my command. Thus I use PS4 bash environment variables giving here

PS1="[\u@\h \W]\\$ "
PS4=:\D{%F %T}: ; set -x

what gives me the following prompt

[user@host temp]$ \ls
:2012-04-10 13:43:52: ls
dir1  dir12  test
[user@host temp]$

In an other hand, I would like to have my path not too long when I am in a deep directory (it is to say very often). I found the following code (I don't remember where) which is very good

bash_prompt_command() {
# How many characters of the $PWD should be kept
local pwdmaxlen=25
# Indicate that there has been dir truncation
local trunc_symbol=".."
local dir=${PWD##*/}
pwdmaxlen=$(( ( pwdmaxlen < ${#dir} ) ? ${#dir} : pwdmaxlen ))
NEW_PWD=${PWD/#$HOME/\~}
local pwdoffset=$(( ${#NEW_PWD} - pwdmaxlen ))
if [ ${pwdoffset} -gt "0" ]
then
    NEW_PWD=${NEW_PWD:$pwdoffset:$pwdmaxlen}
    NEW_PWD=${trunc_symbol}/${NEW_PWD#*/}
fi
}
PS1="[\u@\h \${NEW_PWD}]\\$ "
PROMPT_COMMAND=bash_prompt_command

which gives me the following

[user@host semishort_path]$ 

The problem occurs when I use both PS4 and PROMPT_COMMAND what gives me that horrible thing :

[user@host temp]$ \ls
:2012-04-10 13:48:32: ls
dir1  dir12  test
::2012-04-10 13:48:32: bash_prompt_command
::2012-04-10 13:48:32: local pwdmaxlen=25
::2012-04-10 13:48:32: local trunc_symbol=..
::2012-04-10 13:48:32: local dir=temp
::2012-04-10 13:48:32: pwdmaxlen=25
::2012-04-10 13:48:32: NEW_PWD='~/temp'
::2012-04-10 13:48:32: local pwdoffset=-19
::2012-04-10 13:48:32: '[' -19 -gt 0 ']'
[user@host temp]$ 

Commands used in the PROMPT_COMMAND function are displayed by PS4.

I am looking for a way to avoid this effect :

  • by displaying the real time (updated each second on the same prompt line) in my prompt (PS1 or PROMPT_COMMAND)
  • Find another way to reduce the path length (I need to have the last two directories printed out when I am not at ~)
  • maybe other ideas ???

I know this is a tricky problem, but I thing BASH should be able to do what I want !

Was it helpful?

Solution

The simplest method, is execute a code before each command

function tsprint() {
        if [[ $BASH_COMMAND != bash_prompt_command ]]
        then
                echo $(date) ": $BASH_COMMAND"
        fi
}
PS1="[\u@\h \${NEW_PWD}]\\$ "
PROMPT_COMMAND="bash_prompt_command;trap 'tsprint; trap DEBUG' DEBUG"

Here the sample output:

[shaman@shamanbook ~]$ cd Music/
Fri Apr 13 02:22:34 EEST 2012 : cd Music/
[shaman@shamanbook ~]$ ls
Fri Apr 13 02:22:34 EEST 2012 : ls --color=auto
[shaman@shamanbook ~/Music]$
[shaman@shamanbook ~/Music]$ pwd
Fri Apr 13 02:22:39 EEST 2012 : pwd
/home/shaman/Music
[shaman@shamanbook ~/Music]$
[shaman@shamanbook ~/Music]$
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top