One solution would be to rewrite history so that when you run this:
ls
it gets saved as:
cd /current/directory && ls
For Bash there is a trick to modify its history, as explained in this great stackoverflow answer. You'll need to use a Bash shell variable called PROMPT_COMMAND
.
When set, its contents are executed every time before the prompt is shown. Setting it to this:
export PROMPT_COMMAND='hcmd=$(history 1); hcmd="${hcmd# *[0-9]* }"; if [[ ${hcmd%% *} == "cd" ]]; then pwd=$OLDPWD; else pwd=$PWD; fi; hcmd=$(echo -e "cd $pwd && $hcmd"); history -s "$hcmd"'
will rewrite history as described above.
Try it first in a Terminal window and if you are happy with it, add it to your .bashrc
file to enable it.
The downside is that, in its current incarnation, all commands will be prefixed with cd /some/dir
, which decreases readability and can get annoying for commands like cd /usr/local
:
$ history | tail -n 5
522 cd /Users/jaume && cd /usr/local
523 cd /usr/local && file bin/ls
524 cd /usr/local && cd ~
525 cd /Users/jaume && file Documents/.localized
526 history | tail -n 5
You could of course modify PROMPT_COMMAND
to only rewrite history for a reduced number of commands.
In your question, you imply that you're not quoting the line at all; that's clearly wrong, because then the space would separate the argument assignment "PS1=[\u@\h" from the command "\W]\$". Please realise that every character is important.
Anyway, what you're probably doing is using double quotes (") rather than single ones ('). They behave very different when it comes to the shell interpreting what you typed. With double quotes, it will try to do clever things with the sequences of backslash/some-character. For this assignment, since there's nothing special about \u, \h, and \W, they're left untouched; square brackets can have special meanings in various places, but not in this case, so they're also left in place; but since a $
has a variety of meanings, all of them special, the \$
sequence is interpreted as "ignore the specialness of the dollar sign, and just leave it there", and that sequence is replaced with a no-further-parsed single dollar sign. The result of all of that is assigned to PS1
, and since there's a literal dollar sign, and not the magic \$
sequence when the shell constructs the actual prompt, you just get the dollar sign, and not the effective-user-dependent character. The actual parsing is a bit more complicated, but that's the gist of it for this particular example.
What you typed: PS1="[\u@\h \W]\$ "
What the shell assigned: PS1 <- "[\u@\h \W]$ "
What you wanted: PS1 <- "[\u@\h \W]\$ "
What you should type: PS1='[\u@\h \W]\$ '
What you should do next: Read something like this tutorial to learn more about shell quoting.
Best Answer
Just replace
\w
with\$PWD
:Anyway if you mind a little tip, I'd write something like: