Shell

Created · Updated

A shell is a program that reads commands as text and turns them into system calls that start other programs and connect them. The kernel offers mechanisms: create a process, run a program in it, open a file, make a pipe, send a signal. It doesn’t understand text such as cat log | grep ERROR > errors.txt. Without a shell, each such task would need its own small program that makes those system calls. A shell is a process like any other, outside the kernel; the name pictures it as the outer layer around the kernel.

A shell is three things at once:

  • A loop: read a line, parse it, start the programs, wait for them, read the next line.
  • A language: variables, quoting, * patterns, if and loops, and the syntax that connects programs, |, >, <, and &&.
  • A parent process: every command it runs is its child, and the shell collects each child’s exit code.

Running a command

  • The shell splits the line into words. The first word names the program, and the shell looks for it in each directory listed in the PATH variable.
  • It makes a copy of itself, a child process, with fork(). On Linux, C libraries make this copy with the clone() system call, which is the name a trace shows.
  • The child calls execve(), which replaces the program running in a process with another one. The process keeps its process ID (PID), so the child is now the command, under the PID the shell created.
  • The shell waits for the child to end with wait(), then stores the child’s exit code in the variable $?.
  • A few commands, the builtins, run inside the shell itself without a child, because they change the shell’s own state. cd is one: a child that changed directory would change only its own.

Pipes and redirection

A process reads and writes through file descriptors, small numbers that each refer to an open file or pipe. Every program starts with three: 0 is standard input (stdin), 1 is standard output (stdout), and 2 is standard error. A pipe is a kernel buffer with two ends, one to write into and one to read from. |, >, and < are shell syntax: the shell creates the pipe or opens the file, then sets each child’s descriptors 0 and 1 before the child runs its program.

Tracing sh -c "cat /etc/passwd | grep root > /tmp/out" on Alpine showed these system calls, in this order:

ProcessSystem callWhat it does
Shellpipe2Makes a pipe. Its read end is descriptor 3, its write end 4.
ShellcloneStarts a child for cat.
cat childdup3(4, 1)Copies descriptor 4 onto 1, so its stdout is the pipe’s write end.
cat childexecveBecomes /bin/cat.
ShellcloneStarts a child for grep.
grep childdup3(3, 0)Its stdin is now the pipe’s read end.
grep childopenatOpens /tmp/out for writing, created or emptied, for >.
grep childdup3(3, 1)Its stdout is now that file.
grep childexecveBecomes /bin/grep.
Shellwait4Waits for both children.
  • cat reads /etc/passwd and writes to descriptor 1. grep reads descriptor 0 and writes to descriptor 1. Neither knows about the pipe or the file.
  • Each child closed the descriptors it no longer needed, and the shell closed both pipe ends. A reader sees end-of-file only when every write end is closed, so one forgotten copy would leave grep waiting forever.
  • /tmp/out got descriptor 3 because 3 was free again in the grep child after it closed its copy of the pipe.

Running a program without a shell

  • Any process can call execve() itself. A shell is needed only for its language: pipes, redirection, variables, and patterns.
  • Go’s os/exec package “intentionally does not invoke the system shell”. exec.Command("ls", "-l") runs ls with no shell. exec.Command("ls", "*.go") passes the literal text *.go, because expanding * is a shell feature.
  • exec.Command("sh", "-c", "ls -l | grep main") starts a shell on purpose, so it can interpret the pipe. -c tells the shell to run the next argument as a command line and then exit.
  • The shell’s own exec builtin skips the child: exec nginx makes the shell call execve() in its own process, so nginx takes over the shell’s PID and the shell is gone.

Shell form and exec form

A Dockerfile’s ENTRYPOINT sets the program a container runs. It has two forms, and only one starts a shell:

# Exec form: Docker runs nginx directly.
ENTRYPOINT ["nginx", "-g", "daemon off;"]

# Shell form: Docker runs /bin/sh -c 'nginx -g "daemon off;"'.
ENTRYPOINT nginx -g "daemon off;"
  • The exec form is a list of words, the program and its arguments, with no shell and no variable expansion.
  • The shell form is one line of text. Docker stores it as ["/bin/sh", "-c", "nginx -g \"daemon off;\""], so the container starts a shell, which then starts nginx.
  • The shell form of ENTRYPOINT ignores CMD and arguments given to docker run.
  • CMD has the same two forms: CMD ["nginx", "-g", "daemon off;"] and CMD nginx -g "daemon off;".
  • -g "daemon off;" keeps nginx in the foreground. Without it, nginx would start a background copy of itself and exit, and the container would stop.

Why PID 1 matters

  • The container’s first process gets PID 1 inside the container. The kernel delivers a signal to PID 1 only if that process installed a handler for it.
  • docker stop and Kubernetes stop a container by sending SIGTERM to PID 1. After a grace period, 10 seconds for docker stop and 30 for Kubernetes by default, they send SIGKILL, which can’t be blocked.
  • A shell waiting for its child has no SIGTERM handler. As PID 1, it ignores SIGTERM, and it doesn’t pass the signal to its child either.
  • So when the shell form leaves a shell as PID 1, the program never sees SIGTERM. It gets no chance to shut down cleanly and is killed at the end of the grace period.

When the shell stays

Some shells skip the child for the last command of a -c command line: they call execve() for it directly, as if it began with exec. Then no shell is left. Containers started with sh -c or bash -c and the command lines below had this as PID 1. sh -c or bash -c in a cell means the shell stayed; sleep means it replaced itself.

Command lineBusyBox sh 1.37 (Alpine)dash 0.5.12 (Debian)bash 5.2
sleep 1000sleepsh -csleep
echo start; sleep 1000sleepsh -csleep
T=1000; sleep $Tsleepsh -csleep
sleep 1000 > /tmp/xsleepsh -cbash -c
sleep 1000 | catsh -csh -cbash -c
echo start; exec sleep 1000sleepsleepsleep
  • BusyBox is /bin/sh in Alpine images, and dash is /bin/sh in Debian and Ubuntu images. dash stayed every time unless the line used exec.
  • A pipe always kept the shell, since it has to start and wait for two children.
  • The Dockerfile reference says a shell-form program “will not be the container’s PID 1”. That held for dash but not for BusyBox, so the same Dockerfile line behaves differently on Debian and Alpine images.

A script file behaves differently from -c. A container running /bin/sh /start.sh kept the shell as PID 1 in both BusyBox and dash when the script’s last line was a plain command. It was replaced only when that line began with exec.

Stopping nginx

nginx shuts down cleanly and exits with 0 when it receives SIGTERM. Six images, built on nginx:1.27 (Debian) or nginx:alpine, were each stopped with docker stop. They shared these lines:

FROM nginx:1.27
STOPSIGNAL SIGTERM
COPY start.sh start-exec.sh /

STOPSIGNAL sets the signal docker stop sends first. The nginx images set it to SIGQUIT, nginx’s signal for a graceful shutdown, so the tests set it back to SIGTERM, the default. Each image then had one ENTRYPOINT: the exec form, the shell form, or a script in exec form, ENTRYPOINT ["/start.sh"] or ENTRYPOINT ["/start-exec.sh"]. The two scripts differ only in their last line:

#!/bin/sh
# start.sh
echo starting
nginx -g "daemon off;"
#!/bin/sh
# start-exec.sh
echo starting
exec nginx -g "daemon off;"
Image and ENTRYPOINTPID 1Stop tookExit code
Debian, exec formnginx0.2 s0
Debian, shell formsh -c10.2 s137
Debian, start.shsh start.sh10.2 s137
Debian, start-exec.shnginx0.2 s0
Alpine, shell formnginx0.2 s0
Alpine, start.shsh start.sh10.2 s137
  • With nginx as PID 1, it received SIGTERM, shut down, and exited with 0 in 0.2 seconds.
  • With a shell as PID 1, nginx never received SIGTERM. SIGKILL ended the container after the 10-second grace period, and the exit code was 137, which means killed by SIGKILL.
  • The Alpine shell form worked only because BusyBox replaced itself with nginx. The Debian shell form, with the same Dockerfile line, didn’t.

Keeping the signal path

These arrangements let SIGTERM reach the program:

  • The exec form of ENTRYPOINT or CMD: the program is PID 1.
  • exec on the last line of a wrapper script: the script does its setup, then the program replaces the shell.
  • A script that stays as PID 1, for example to run cleanup after the program exits, installs a handler with the trap builtin and sends the signal on to the program itself.
  • A small init process, such as tini (docker run --init): it runs as PID 1 and forwards signals to its child.

In Kubernetes, a preStop hook is a command the kubelet runs in the container before it sends SIGTERM. A hook that sends SIGTERM to the program also reaches it past a shell, but the shell stays in the way of every other signal.

References: execve(2), fork(2), pipe(2), dup(2), POSIX Shell Command Language, dash(1), Go os/exec, Dockerfile reference, pid_namespaces(7), Container lifecycle hooks