Change prompt formatting based on cwd

prompttcsh

I use tcsh. I'd like to have my prompt formatting (coloring/highlighting) change based on the directory I'm in, or other critical aspects of my environment.

I'm not enough of a shell hacker to know how to do this.

Ownership of Current Directory

If I'm in one of "my" directories (i.e., I am owner of the current working directory), then it should have normal appearance. But if I'm in someone else's directory (I do a lot of support and cd to others' working areas), then I want the prompt to look clearly different.

This is to remind me to not type impolite commands in others' directories. (think make clobber or p4 sync, etc.)

Critical Environment Variable Setting

Another important piece of information for my environment is whether a certain environment variable is set, call it SWDEV. If SWDEV is not set, then my scripts and flows come from their default location. But if this variable is set, then it's taken as a new root location for my scripts and flows, with behaviors changing according to the scripts at that location.

It's important to be reminded of the setting of this variable, lest I expect "normal" behavior but instead absentmindedly run code from the new location.

Best Answer

Well, if an external script is an acceptable solution, you could do something like this:

#!/usr/bin/env perl 
use Cwd;
my $cwd=getcwd();
$cwd =~ /$ENV{HOME}/ ? 
             print "$cwd % " : 
             print "%{\033[1;31m%}CAREFUL\\\!%{\033[0m%} $cwd % ";

Save that somewhere in your $PATH as make_prompt.pl and make it executable. And then, in your ~/.tcshrc :

alias precmd 'set prompt="`make_prompt.pl`"'

This will result in:

                     enter image description here

You can also add more conditions to change the prompt in specific ways in different directories:

#!/usr/bin/env perl 
use Cwd;
my $cwd=getcwd();

## Here are some colors to choose from
my $red="%{\033[1;31m%}";
my $green="%{\033[0;32m%}";
my $yellow="%{\033[1;33m%}";
my $blue="%{\033[1;34m%}";
my $magenta="%{\033[1;35m%}";
my $cyan="%{\033[1;36m%}";
my $white="%{\033[0;37m%}";
## This resets the color, you need it after each color command
my $end="%{\033[0m%}";


## If you are in $HOME or one of its sub dirs, print a green prompt
if($cwd =~ /$ENV{HOME}/){
   print "$green$cwd$end % ";
}
## If you are in /usr or one of its sub dirs, print a red prompt
elsif($cwd=~ /\/usr/){
   print "$red$cwd$end % ";
}
## If you are in /etc or one of its sub dirs, print a blue prompt
elsif($cwd=~/\/etc/){
    print "$blue$cwd$end % ";
}
## If you're in /root. As you can see, colors can be combined
elsif($cwd=~/\/root/){
    print $red . "OY\\! You're not allowed in here\\!" . 
          $end . $magenta . " $cwd$end % ";

}
## For wherever else, just print a plain prompt
else {
    print "$cwd % ";
}
Related Question