Friday, August 05, 2011

bash initialisation files

I've been installing Centos 5 into VirtualBox this evening. Due to some mistyping, I ended up in the situation where I needed to manually create the 'home' directory for the user 'nwsmith'. Ok, thats simple, just remember to set the correct user and group, and the correct permissions:

# mkdir /home/nwsmith
# chown nwsmith.nwsmith /home/nwsmith
# chmod 700 /home/nwsmith

But when I logged in as user 'nwsmith' I was not getting the correct bash prompt. It looked like PS1 was not being set correctly. I quickly realised that I was missing the '.bashrc' file from my home directory, so I copied that across from '/etc/skel/.bashrc'.

But still I was not getting the correct prompt. But I found that if I ran the command 'source ./.bashrc' then I did get the correct prompt. Finally the penny dropped, when I googled up this link Initialisation files and configuration from the University of Cambridge Computer Laboratory. I'm just going to quote the paragraph I found really useful:

When bash is invoked as a login shell it first reads and executes commands from the file /etc/profile, if that file exists. This initialises a few environment variables, and calls a set of small initialisation scripts from the directory /etc/profile.d, which will vary depending on the software loaded on the machine (for example, if KDE is loaded there will be one called kde.sh).

After reading that file, it looks for ~/.bash_profile or ~/.bash_login or ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. (The --noprofile option could be used when the shell is started to inhibit this behaviour.)

When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. (This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc).

Thus, by default, the file ~/.bashrc is not read automatically when a login shell is started. For this reason it is usual behaviour to add a section to ~/.profile (or ~/.bash_profile or ~/.bash_login) to read and execute it, so that you get uniform behaviour on both login shells and normal interactive shells.

After reading that I realised that I also need a '.bash_profile' file in my home directory, so I copied one across from '/etc/skel/.bash_profile'. And then when I logged in as user 'nwsmith' I got the prompt I was expecting.

By the way, '.bash_profile' and '.bashrc' do NOT need to have 'x' executable permission.

No comments: