ytbryan
ytbryan

Reputation: 2694

How can I get 'system("source ~/.bash_profile")' to work with current shell?

I am updating the bash file programmatically. And at the end of the script, I called system("source ~/.bash_profile") to source the bash file. However, the bash file did not get updated in the current shell.

After some research, I found out that system() executes within a subshell. Hence (I think) the current shell is not updated with the latest bash file.

It seems that other methods of calling shell commands do not execute them in the current shell too. i.e. backtick, exec, open3, open4.

How do I call a shell command that will update the current shell, without opening a new shell (to break the current work flow)?

I am looking at these commands including

source ~/.bash_profile

or

alias something="echo something"

Update: The suggested answer works. Hence, I am calling system("kill -SIGUSR1 #{Process.ppid}") to source the .bash_profile. Note that if you are on mac, you should place the suggested code on .bash_profile instead of .bashrc

Upvotes: 1

Views: 607

Answers (2)

Hans Klünder
Hans Klünder

Reputation: 2292

In your .bashrc.bash_profile:

sigusr1() {
   source ~/.bash_profile
   echo 'wow! I feel refreshed!'
}

trap sigusr1 SIGUSR1

Now, from your program, find out the bash pid (may be just getppid()) and send SIGUSR1 to it using kill().

You'll have fun if you shoot the wrong process! It's some way to make new contacts, especially to those people who just got their processes killed.

Upvotes: 1

Etan Reisner
Etan Reisner

Reputation: 81052

You cannot, from a program run from the shell, source a script in the parent shell.

That source command or a similar alias will, when run from the shell directly, cause the changes to take effect in the current shell though. But in that case you need to write your profile/rc carefully so as to be safe to re-run that way.

Upvotes: 0

Related Questions