In Windows CMD.EXE, I have my prompt string set to $P$G
,
so, if my current working directory is
C:\Some\long\folder\inner
my prompt is like this:
C:\Some\long\folder\inner>
I want it to show only the last (lowest level) folder name, like this:
inner>
where "inner" is just the name of the inner-most folder,
and it should automatically change to the inner-most folder of
whichever directory I'm currently inside –
equivalent to the capability discussed in
Show only current directory name (not full path) on bash prompt.
How can I do this?
Best Answer
Here's a workaround, if you're willing to change your habits a little.
First of all, pick a directory in your PATH that you can write to. Assuming that you're on your own machine, and you have admin rights, you could use
\Windows
or\Program Files\something
. But it's probably better to use something like\Users\username\bin
. (Add it to your PATH if you don't already have it there.)Then create a file there called
CH.BAT
, or something like that, with the following contents:And then get into the habit of typing
ch
instead ofcd
(orchdir
, if you're old enough to remember its original name (which is still supported)). I believe that the comments explain it fairly well, but, to recapitulate:cd
on the command-line argument(s). If it fails, exit the script.%varname:old=new%
) to strip off directory levels. Loop until there's nothing left to do. If the current directory is the root (e.g.,C:\
), then the prompt will beC:\>
(since you didn't specify how to handle that case). If it is something likeC:\top\outer\middle\inner
, you will getinner>
, as requested.$$
in the prompt, it will display as$
. So we replace all dollar sign(s) in the directory name with$$
to get them to display correctly.cd
instead ofch
, your prompt will not change. If this happens, just typech
(orch .
) to set the prompt based on the new current directory.cd
(orecho %CD%
).Naturally, it does no good to name the script
CD.BAT
orCHDIR.BAT
, because CMD.EXE always interpretscd
andchdir
as the “change directory” built-in command. You can run such a script by typing its pathname, but obviously that’s infeasible (from a workflow perspective) as an override/replacement forcd
.