What is the purpose of .bashrc and how does it work?

  • I found the .bashrc file and I want to know the purpose/function of it. Also how and when is it used?

    You run it as `$ bash myFile.bashrc`. I found this to be missing :)

  • .bashrc is a shell script that Bash runs whenever it is started interactively. It initializes an interactive shell session. You can put any command in that file that you could type at the command prompt.

    You put commands here to set up the shell for use in your particular environment, or to customize things to your preferences. A common thing to put in .bashrc are aliases that you want to always be available.

    .bashrc runs on every interactive shell launch. If you say:

    $ bash ; bash ; bash
    

    and then hit Ctrl-D three times, .bashrc will run three times. But if you say this instead:

    $ bash -c exit ; bash -c exit ; bash -c exit
    

    then .bashrc won't run at all, since -c makes the Bash call non-interactive. The same is true when you run a shell script from a file.

    Contrast .bash_profile and .profile which are only run at the start of a new login shell. (bash -l) You choose whether a command goes in .bashrc vs .bash_profile depending on on whether you want it to run once or for every interactive shell start.

    As a counterexample to aliases, which I prefer to put in .bashrc, you want to do PATH adjustments in .bash_profile instead, since these changes are typically not idempotent:

    export PATH="$PATH:/some/addition"
    

    If you put that in .bashrc instead, every time you launched an interactive sub-shell, :/some/addition would get tacked on to the end of the PATH again, creating extra work for the shell when you mistype a command.

    You get a new interactive Bash shell whenever you shell out of vi with :sh, for example.

    Minor quibble: unlike most other shells, bash does *not* automatically load the per-instance config file `.bashrc` when it's started as a login shell. This can sometimes lead to unexpected behavior. The usual workaround is to source `.bashrc` from `.profile` or `.bash_profile` instead.

    @IlmariKaronen Since `.bashrc` isn't intended for use by other shells, it's better not to source it from `.profile` (which might be used by other non-`bash` shells).

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM