Ubuntu – Cannot successfully source .bashrc from a shell script

bashbashrcscripts

Normally we can source ~/.bashrc file using this command

source ~/.bashrc

but if I write this in a shell script and execute it, nothing happens. Why?
Is there any way to do this?

My script:

#!/bin/bash
chmod a+x ~/.bashrc
source ~/.bashrc

Also tried . (dot) instead of source. Same result.

Best Answer

A shell script is run in its own shell instance. All the variable settings, function definitions and such only affect this instance (and maybe its children) but not the calling shell so they are gone after the script finished.

By contrast the source command doesn't start a new shell instance but uses the current shell so the changes remain.

If you want a shortcut to read your .bashrc use a shell function or an alias instead of a shell script, like

alias brc='source ~/.bashrc'