I have found that in bash i frequently use something like that:
- vim ./somefile1 less
- less ./dir1/dir2/somefile2
- cp some_other_relative_path_to_file
and so on
After that when I trying to find a command in history and run it I get an error because I am in a different directory now. Is it possible to configure bash to "expand" relative path to files with absolute one when they go to history?
Best Answer
One solution would be to rewrite history so that when you run this:
it gets saved as:
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:
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 likecd /usr/local
:You could of course modify
PROMPT_COMMAND
to only rewrite history for a reduced number of commands.