tags:

views:

679

answers:

4

In my current situation, it is not unusual for me to have several UNIX computers I connect to, as several different users depending on the situation, and to traverse through various directories on the machines doing things. I use ksh through the entire thing.

I was fiddling with my prompt recently, and I was able to get it to change some colors depending on my current username and current server. However, what I would also want is for it to change colors based on my current directory. For example, if I were in directory "foo", the prompt should be yellow, but if I were in directory "bar", the prompt would be magenta. In both cases, subdirectories should also count, so a simple substring check should be enough.

The problem I ran into, however, is that when I run my .profile script, it properly colors the directory--but it no longer dynamically updates whenever I switch to another directory--and I'm not sure how before I did all the branching, I was able to get it to print my current working directory correctly even after I switched directories.

I did some googling, and find information for bash, but ksh seems to be largely ignored. As I cannot figure out how to do this on my own, I must bring it to the Stack Overflow community, to add it to future knowledge. Thus, with my long-winded explanation, the "quick version" of my question is as follows:

In ksh, how can I set up my prompt to display the current working directory and color the text based on where the current working directory is? Is it even possible?

+1  A: 

Why not using zsh? It is based on ksh, and it is much more powerful. In zsh you can write chpwd function that is implicitly called every time you change directory. In this function you can check your current directory and set PS1 to whatever you want.

Alternatively (even in ksh) you can create an alias for cd command:

change_my_ps() {
  PS1=...
}
better_cd() {
  builtin cd "$@"
  change_my_ps
}
alias cd=better_cd

Something like this. I'm not sure it is proper, I don't remember ksh syntax.

stepancheg
A: 

I use this:

function chdir
{
   cd "$@"
   CWDH=${PWD%/*}
   PS1="($_time)$hname:${CWDH##*/}/${PWD##*/} ->"
   export PS1
}
alias cd=chdir
chdir .

Ignore the time and hname, but the rest should work for you. Changing colors is going to be terminal dependent. You need to know the escape codes for each color for the terminal you will be using. If you know you only ever use an xterm, it will be easier.

bobmcn
A: 

To display the current directory in ksh, put this in your .profile file: export PS1="\$PWD " That will dynamically update when you change directory without mucking around with functions.

Alex D

related questions