Setting a part of a PWD as a prompt and keeping a

2019-07-04 10:37发布

问题:

I'm using tcsh, and I'm trying to set a part of the PWD to appear always in the prompt (so I will always know in which "parent" directory I am).

I managed to extract the needed part of the prompt in the following way, and it works fine (I call it MyTreePath):

set MyTreePath=`echo $PWD | awk '{... print whichTree}'`

I've added the code above to my .tcshrc and I've added %$MyTreePath to my set prompt line in .tcshrc.

The problem is that once the shell is opened, the MyTreePath doesn't change, even if I'm going to a totally different path.

How to keep a variable that appears in the prompt updated?

回答1:

Use the magical cwdcmd alias! It is used for defining a command which executes everytime the cwd changes. In your case, you need to updated your variable.

From the manpage:

The beepcmd, cwdcmd, periodic, precmd, postcmd, and jobcmd Special aliases can be set, respectively, to execute commands when the shell wants to ring the bell, when the working directory changes, every tperiod minutes, before each prompt, before each command gets executed, after each command gets executed, and when a job is started or is brought into the foreground.

Here's a quick example:

alias cwdcmd 'set FOO=`pwd`'
set prompt='%$FOO >>>      '

field testing:

cd /
/ >>>      cd dev
/dev >>>

So all that's left is to replace pwd in the alias above with your own command.

For more info and other magic aliases, see here.