Set PROMPT_COMMAND and PS4 (having command start date and hard print path)
I am trying to show the execution date of my command. So I am using PS4 bash environment variables by providing here
PS1="[\u@\h \W]\\$ "
PS4=:\D{%F %T}: ; set -x
which gives me the following prompt
[user@host temp]$ \ls
:2012-04-10 13:43:52: ls
dir1 dir12 test
[user@host temp]$
In the other hand, I would like my path not to be too long when I'm in a deep directory (this is very common). 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, which gives me this awful 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]$
The commands used in the PROMPT_COMMAND function are displayed on the PS4.
I am looking for a way to avoid this effect:
- displaying real time (updated every second on the same prompt line) in my prompt (PS1 or PROMPT_COMMAND)
- Find another way to reduce the length of the path (I need the last two directories to be printed when I'm not on ~)
- maybe other ideas.
I know this is a tricky problem, but my bash thing should be able to do what I want!
+3
source to share
1 answer
The easiest way is to execute the 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's 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]$
+3
source to share