Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "source" ~/.bashrc automatically once it has been edited?

Tags:

alias

bash

macos

I would like to create an alias that does the following:

  • Opens TextMate with ~/.bashrc and allows me to edit it
  • Once I close TextMate, "sources" ~/.bashrc (so if I add a new alias, for example, it will be available immediately)

I tried the following:

alias b="/usr/bin/mate -w ~/.bashrc; source ~/.bashrc"

but it doesn't work: when I close TextMate, the shell doesn't return.

Any ideas?

like image 814
Misha Moroshko Avatar asked Oct 19 '25 08:10

Misha Moroshko


1 Answers

I hesitate to suggest it, but if this is a feature you really want, you can make something similar happen by setting the PROMPT_COMMAND variable to something clever.

PROMPT_COMMAND is run every time the shell shows the shell prompt So, if you're okay with the shells updating only after you hit Enter or execute a command, this should nearly do it.

Put export PROMPT_COMMAND="source ~/.bashrc" into your ~/.bashrc file. Re-source it into whichever shell sessions you want the automatically updating behavior to work in.

This is wasteful -- it re-sources the file with every prompt. If you can get your editor to leave the old version in a specific file, say ~/.bashrc~ (where the first ~ means your home directory and the last ~ is just a ~, a common choice for backup filenames) then you could do something more like (untested):

export PROMPT_COMMAND="[ ~/.bashrc -nt ~/.bashrc~ ] && touch ~/.bashrc~ && source ~/.bashrc "

then it would stat(2) the two files on every run, check which one is newer, and re-source only if the ~/.bashrc is newer than its backup. The touch command is in there to make the backup look newer and fail the test again.

like image 97
sarnold Avatar answered Oct 21 '25 22:10

sarnold