Skip to content

Instantly share code, notes, and snippets.

@caruccio
Last active June 25, 2019 13:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caruccio/bb4ffa9833d7057e785bf2a1b664d531 to your computer and use it in GitHub Desktop.
Save caruccio/bb4ffa9833d7057e785bf2a1b664d531 to your computer and use it in GitHub Desktop.
Reload shell config in-place
## Ever had to add something to your shell's config files (i.e. .bashrc)
## and open a new shell? Well, that may be fine, but you can achieve the
## same result, plus without having to open a new window/tab
## or execute a child process.
##
## Idea taken from https://learn.hashicorp.com/vault/getting-started/install
## lets check if any command `hello` exists
$ hello
bash: hello: command not found
## what shell are we?
$ echo $SHELL
/usr/local/bin/bash
## since it's bash, let's add an alias `hello`
$ echo 'alias hello="echo world!"' >> ~/.bashrc
## it's not enough to add it to configs. The config must be reexecuted somehow
$ hello
bash: hello: command not found
## what's the bash PID?
$ echo $$
78047
## here is the trick.
## `exec` will replace current bash by a new bash, with same PID.
## all bash config files are executed as if it was a new bash, which
## in fact it is!
## the downside is that anything you defined by hand will be lost :(
$ exec $SHELL
## Yup, same PID
$ echo $$
78047
## and now we have an updated bash instance without creating a child process
$ hello
world!
@josebraga
Copy link

Hi, was looking at some examples of bash path vars and found this.. you can also reload .bashrc:
source ~/.bashrc

@caruccio
Copy link
Author

Hi, was looking at some examples of bash path vars and found this.. you can also reload .bashrc:
source ~/.bashrc

Yep that works just fine. However the current state of the shell will remain, like local vars, aliases, and functions.
Depends on what you need at the moment.

$ x=1
$ echo "[$x]"
[1]
$ source ~/.bashrc  ## adds/replace at the current shell
$ echo "[$x]"
[]
$
$ x=1
$ echo "[$x]"
[1]
$ exec $SHELL     ## replaces the current shell
$ echo "[$x]"
[]
$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment