3

I have the following code in my .profile:

case $TERM in
    xterm*)
        HOST=`hostname`
        PS1='^[]0;${USER}@${HOST}: ${PWD}^Gksh$ '
        ;;
    *)
        PS1='ksh$ '
        ;;
esac

This works fine unless the path gets too long. Is there an alternative way of doing something similar but—when the paths are long—it displays .../<end of the path> so that it works?

2

Here are two alternatives, depending on your end goal.

Only show the trailing directory element

PS1='^[]0;${USER}@${HOST}: ${PWD##*/}^Gksh$ '

This simply introduces the ## parameter substitution to your existing PS1 in order to greedily strip away characters until the final forward slash. This will shorten the PWD portion of the PS1 prompt string regardless of length.

Only shorten long PWD strings

Full disclosure, I got the "bones" of this from one of the answers to this Stack Overflow question:

How to custom display prompt in KornShell to show hostname and current directory?

... then modified it accordingly. In short, it aliases cd to an internal function. That function emulates the original cd behavior but then does some string "math" to determine the new PS1 prompt. I took your question rather literally, so if you don't want "..." prefixing the long directory names, remove that string from the P=... line and also remove the +3 in the math line above it.

function _cd {
   directory=$1
   pattern=$2

   # First cd to the directory
   if [ "$pattern" ]
   then
       \cd "$directory" "$pattern"
   elif [ "$directory" ]
   then
       \cd "$directory"
   else
       \cd
   fi

   # set this value to taste
   MAXLEN=20
   LEN=${#PWD}
   P=$PWD
   # if PWD is "too" long, trim it
   if [ $LEN -gt $MAXLEN ]
   then
     # the 3 is for the literal "..."
     START=$(( LEN - MAXLEN + 3 ))
     P="..."$(echo $PWD | cut -c ${START}-)
   fi
   PS1="^[]0;${USER}@${HOST}: $P^Gksh\$ "
}

alias cd="_cd"

Of course, as I write this up, a third option comes to mind -- to use the alias/internal-function code, but instead of cuting the string, use the ## parameter substitution in it to strip directory elements as in the first example.

0

The best way that I have found is to use a ksh93 discipline function on the PS1 environmental variable:

# set ksh prompt and xterm title
_PSX='$( p="${PWD/~(El)${HOME}/\~}"
     printf "%s@%s:%s" "${LOGNAME}" "$(hostname -s)" "${p}"
)'

function PS1.get
{
    .sh.value="ESC]0;${_PSX}^G${_PSX}$ " 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.