Linux Startup Process – When Does a Shell Get Executed

Architecturelinuxshellstartup

I do not understand when does a shell, lets say bash, get executed, which program runs bash initially first.

Best Answer

The boot sequence of linux/unix has many stages, and there are many references and answers on this site that explain the detail. But to summarise;

Eventually the kernel is loaded with drivers so that the disk and devices can be used, it then starts process with a pid (process id) of 1.

Traditionally this program was a program called init but today there are several newer programs (systemd or upstart). It depends on your distribution and version, which one is used.

Starting up is a tiered process.

There is a concept of escalating run levels (1,2,3,4,5,6 ...) and the start up program will flip between these levels automatically or staged (so that the user can gain control).

  1. being the initial step (single user mode),
  2. multi user mode,
  3. multi user with networking
  4. GUI mode ...
  5. .. 6., ...

These run levels are not fixed in stone either, they depend on the distribution and start up program being used (init, systemd, ...) and convention.

The levels also depend on how the staged start-up/shutdown pattern has been designed. (think, linux is used in routers, android phones, servers and desktops all with different requirements).

In order to transgress from one run-level to another various other programs (services), like bind (for DNS), networking, routing, webservers, ... are started or stopped, and bash may be used then to run a particular script which starts or stops a service.

Eventually you need to login, either at a console or at a graphical interface, and you may be prompt for your username and password.

Let's take a simple route, and say you are at a non-graphical console, and the login program is prompting you to authenticate. When you pass, it will read which shell is configured for the entered username from /etc/passwd and start it, with input and output set to your console and then you have the prompt and can start doing your work. So in this scenario,

init starts -> login which starts -> bash

So every process is a child of the first process, (it might be more accurate to say, every process has pid 1 as an ancestor). In the above example, login will exec the shell, replacing login process with bash, the process id doesn't change. When you look with ps it looks like bash was started by init because it's parent pid is 1, but there was a chain of events.

There's nothing really stopping pid 1 from just starting bash at the console (if pid 1 can work out what the console is at that point) and this is down to how the start-up sequence is designed. (I had to do that once, but it is not normal practice).

Related Question