Skip to content

Instantly share code, notes, and snippets.

@caruccio

caruccio/bash-reload.sh

Last active Jun 25, 2019
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@josebraga josebraga commented Jun 25, 2019

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

@caruccio

This comment has been minimized.

Copy link
Owner Author

@caruccio caruccio commented Jun 25, 2019

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