3.2. Working in the Shell

The shell that an interactive Debian login starts is bash; /bin/sh, used by system scripts and #!/bin/sh program lines, is dash, a smaller and faster interpreter for non-interactive scripts. This section covers the parts of bash that administration exercises daily: how a command line is parsed and expanded, how streams are connected, what the environment carries, and how jobs are controlled from the terminal.

3.2.1. Command Syntax, Quoting, Expansion, and Exit Status

A command line is split into words. The first word names the program - a shell builtin, a function, or an executable found through PATH - and the remaining words are its arguments. By long-standing convention, arguments that adjust behavior look like -n or --long, and arguments that name the things to work on come last. That convention is not a law: each program documents its own syntax, which is one reason the manual pages in Section 3.6 matter.

Before the program runs, the shell rewrites the words through several expansions: brace expansion, tilde expansion (~ to the home directory, already seen in Section 3.1.3), parameter and variable expansion, arithmetic expansion, command substitution, word splitting, and finally pathname expansion - globbing. Quoting controls which of those happen. Double quotes keep the text together but let expansions run; single quotes suppress everything:

$ name=trixie; echo "double: $name $(printf hi)"
double: trixie hi
$ echo 'single: $name $(printf hi)'
single: $name $(printf hi)
Quoting form Effect
'...' Literal: no expansion of any kind happens inside.
"..." One word, but $, backticks, and \ keep their meaning.
\c Escapes the single character c.
$'...' Literal with ANSI-C escapes such as \n and \t.

Expansion itself is easiest to see one form at a time. Brace expansion generates each comma-separated alternative - the file names need not exist:

$ echo brace: {a,b,c}.txt
brace: a.txt b.txt c.txt

Arithmetic between $(( and )) is evaluated:

$ echo arithmetic: $((6*7))
arithmetic: 42

Command substitution runs a command and inserts its output into the line:

$ echo substitution: $(printf one)
substitution: one

The older backtick form does the same but nests badly; new scripts should use $(...):

$ echo backtick: `printf two`
backtick: two

Pathname expansion - globbing - replaces a pattern with the matching file names, and is the expansion that reaches the filesystem. Create three files in the workspace to see it:

$ touch a.txt b.txt c.log

The command completes silently. Now let the shell list the .txt names:

$ echo glob: *.txt
glob: a.txt b.txt

* matches any string, so *.txt expanded to the two matching names and left c.log out. Quoting suspends the expansion - useful when the argument is the pattern, as with find in Section 3.5:

$ echo quoted: "*.txt"
quoted: *.txt

A bracket expression matches one character from the set:

$ echo bracket: [ab].txt
bracket: a.txt b.txt

If a pattern matches nothing, bash leaves it as written - a literal *.txt on a command line usually means a typo or a missing file, not an empty list.

Every command also reports how it ended: the exit status, a small number held in $?. Zero means success; anything else means failure, and scripts branch on that value:

$ bash -c "true; echo true=$?; false; echo false=$?"
true=0
false=1

true and false do nothing except exit with status 0 and 1. Two special statuses come from the shell rather than the program: 127 means the command was not found at all, and 126 means it was found but not executable - Section 3.6.2 shows both, and Section 3.2.4 adds the convention that a process killed by signal N reports 128 + N.

3.2.2. Pipelines, Redirection, and Standard Streams

Every process starts with three open file descriptors: standard input (0), standard output (1), and standard error (2). A program reads its input from descriptor 0 and writes two distinguishable outputs - results on 1 and diagnostics on 2. By default all three connect to the terminal. The shell's | and redirection operators reconnect them before the program starts, which is why the program itself never knows whether it is writing to a screen, a file, or the next stage of a pipeline. Figure 3.2 shows the arrangement.

Standard streams, pipes, and redirections

Figure 3.2. Descriptor 0 feeds a process; descriptors 1 and 2 leave it. Redirection and pipes replace the destinations; the program sees only open descriptors.

A pipeline chains programs by connecting one program's standard output to the next program's standard input:

$ printf "beta\nalpha\ngamma\n" | sort | head -n 2
alpha
beta

printf writes three lines into the pipe, sort reads them and emits them in order, and head -n 2 keeps the first two. Each stage runs concurrently, so long lists stream through instead of waiting for the producer to finish. Standard error is not part of the pipe: a diagnostic printed by the first stage still reaches your terminal, which is usually what you want.

The pipeline's exit status is the last command's by default, which can hide an early failure:

$ false | true; echo "pipestatus=${PIPESTATUS[*]}"
pipestatus=1 0

${PIPESTATUS[*]} holds every stage's status in order - the first stage failed with 1, the last succeeded. For scripts, set -o pipefail makes the whole pipeline fail if any stage fails:

$ set -o pipefail; false | true; echo "status=$?"
status=1

Redirection writes a stream to a file instead of the terminal. The command itself prints nothing when its output goes to a file - the terminal stays silent, and the file is the evidence:

$ printf "first\n" > redirect.txt

> truncates the file first: whatever it contained is gone before the new text is written. >> appends instead. Both forms create the file when it does not exist:

$ printf "second\n" >> redirect.txt

Read the file back with cat to see both lines:

$ cat redirect.txt
first
second
Operator Effect
> file Redirect standard output to file, truncating it first.
>> file Redirect standard output, appending.
2> file Redirect standard error to file.
2>> file Append standard error.
2>&1 Send standard error to wherever standard output now goes.
< file Read standard input from file.
cmd1 | cmd2 Connect cmd1's standard output to cmd2's standard input.
<<EOF / <<'EOF' Feed a here-document as standard input.

Standard error is separate, so it must be redirected separately. Send an error to a file and the terminal shows only the status:

$ ls /no/such 2> err.txt; echo "status=$?"
status=2

The diagnostic itself is in the file:

$ cat err.txt
ls: cannot access '/no/such': No such file or directory

To capture both streams in one file, redirect standard output first and then point standard error at the same place with 2>&1 - the order matters, because 2>&1 duplicates descriptor 2 to wherever descriptor 1 currently points:

$ { printf "out\n"; printf "err\n" >&2; } > combined.txt 2>&1

The braces group the two printf commands so one redirection applies to both; the second printf deliberately writes to descriptor 2. Read the file back:

$ cat combined.txt
out
err

Had the operators been reversed - 2>&1 > combined.txt - standard error would have been copied to the terminal before standard output moved to the file, and the file would hold only out.

tee splits a stream: it writes its input to a named file and passes it through. The next command receives the data, and a copy stays behind:

$ printf "line1\nline2\n" | tee tee.txt >/dev/null

The pass-through end is discarded here with > to /dev/null, a device that accepts and throws away everything written to it - the standard way to silence a stream you genuinely do not want. Confirm the copy:

$ cat tee.txt
line1
line2

A here-document feeds lines of text to a command's standard input without a separate file. The delimiter is quoted (<<'EOF') when the text should survive verbatim, unquoted when it should be expanded like a double-quoted string. The shell reads until a line containing exactly the delimiter:

$ bash <<'EOF'
name="trixie"
printf "hello %s\n" "$name"
EOF
hello trixie

The three lines between the bash command and the closing EOF are the here-document; the inner bash read them as its standard input and ran them, printing the greeting.

3.2.3. Environment Variables, PATH, History, and Completion

A variable assignment such as NOTE=local sets a shell variable, visible only to the current shell. export copies it into the environment, the set of NAME=value strings every new process receives at start-up. Child processes get a copy; they cannot change the caller's values. One line demonstrates both halves - assign, export the second name, and ask a child shell to expand each:

$ NOTE=local; export SHARED=shared; bash -c 'printf "note=<%s> shared=<%s>\n" "$NOTE" "$SHARED"'
note=<> shared=<shared>

The inner bash saw the exported SHARED and expanded it, but NOTE never left the outer shell, so the inner expansion came out empty. Two special variables were already visible in Section 3.1.3 - HOME and USER - set by the login. env lists the whole environment.

PATH is the environment variable the shell uses to find programs: a colon-separated list of directories, searched in order, containing neither your current directory nor a way to say "here". That is why a program in the current directory is run as ./hello.sh and not by bare name. Print it one directory per line:

$ printf "%s\n" "$PATH" | tr : "\n" | nl -ba
     1  /usr/local/bin
     2  /usr/bin
     3  /bin
     4  /usr/games

/usr/local/bin comes first so locally installed software overrides distribution packages; /usr/bin holds the bulk of Debian's programs; /bin is a compatibility link to /usr/bin (Section 3.3.1); administrators sometimes add ~/bin or /usr/sbin for their own tools. Note that sudo does not inherit this list: it substitutes its own secure_path so that elevated commands cannot be tricked into running a program from a user-writable directory.

Which program a name resolves to is answerable directly. command -v prints the path for an external command:

$ command -v ls
/usr/bin/ls

type classifies any name - and reveals that some commands are built into the shell itself:

$ type cd
cd is a shell builtin

echo exists as both, and type -a lists every alternative in the order the shell would use it:

$ type -a echo
echo is a shell builtin
echo is /usr/bin/echo
echo is /bin/echo

The builtin wins, /usr/bin/echo is the external program, and /bin/echo is the same file through the usrmerge link. Bash remembers where it found each external command to avoid repeating the search; after installing a program into an earlier PATH directory, clear that cache with hash -r:

$ hash -r

The command prints nothing; it only resets the remembered locations, so the next invocation searches PATH again.

The shell also remembers what you type. Each interactive command line is appended to the history list and, when the shell exits, to ~/.bash_history. In a fresh shell after three commands, the history builtin lists them with numbers:

$ history
    1  echo alpha
    2  echo beta
    3  history

The number is a reference: !2 re-runs entry 2, !! re-runs the previous command (sudo !! is the habitual repair for a command that needed privilege), and !string re-runs the most recent command starting with string. History expansion is powerful and slightly hazardous - an accidental ! in a command line expands before you can inspect it. Pressing Ctrl+R searches the history interactively instead: type a fragment, and the shell shows the matching line, which Enter runs and Esc edits first.

Tab completion is the other half of not typing. Press Tab once to complete a name that is unambiguous; press it twice to list the alternatives when it is not. The bash-completion package extends this beyond file names - option names for many commands, host names after ssh, service names after systemctl - with the loaded set visible through complete -p, which lists the installed completion specifications:

$ complete -p | wc -l
144

On a standard installation the package is present by default; if complete -p fails, run sudo apt install bash-completion, answer the confirmation prompt, and open a new shell. The installation prints a summary of the packages it adds and finishes on its own; nothing needs to be closed or stopped. Chapter 6 covers package installation in detail.

3.2.4. Foreground Jobs, Background Jobs, and Terminal Control

A terminal runs one foreground process group at a time; the shell is that group when it is waiting at the prompt, and the command you run replaces it until it finishes. Job control is the shell's machinery for suspending, resuming, and backgrounding processes so that the terminal - one keyboard, one screen - can serve several jobs at once. Figure 3.3 shows how the pieces relate.

Foreground and background jobs

Figure 3.3. The terminal driver signals the foreground process group; background jobs keep running and report to the shell. Dashed boxes are the interactive keystrokes described in the text.

The interactive keystrokes are few. Ctrl+C sends SIGINT to the foreground process group, which by convention stops a running program. Ctrl+Z suspends it with SIGTSTP and returns to the prompt; fg resumes it in the foreground and bg resumes it in the background. A job that must keep running after you log out needs nohup, shown below.

A bounded version of "running too long" is worth seeing first. timeout starts a program and kills it when the limit passes:

$ timeout 1 sleep 5; echo "status=$?"
status=124

sleep 5 would have paused five seconds; after one second timeout terminated it and reported its own status 124, the conventional code for "time limit reached". For an unbounded command you would stop with Ctrl+C; in a script, timeout is the programmable equivalent.

The rest of the machinery is most legible as one transcript, from an interactive session in the chapter workspace - the prompt shows the working directory, and $ marks an ordinary shell throughout:

$ ssh john@127.0.0.1
john@trixie:~$ cd ~/debian-handbook/shell-basics
john@trixie:~/debian-handbook/shell-basics$ sleep 30 &
[1] 367524
john@trixie:~/debian-handbook/shell-basics$ jobs -l
[1]+ 367524 Running                 sleep 30 &
john@trixie:~/debian-handbook/shell-basics$ kill %1
john@trixie:~/debian-handbook/shell-basics$ wait %1; echo wait_status=$?
[1]+  Terminated              sleep 30
wait_status=143
john@trixie:~/debian-handbook/shell-basics$ nohup sleep 20 > nohup.out 2>&1 &
[1] 367529
john@trixie:~/debian-handbook/shell-basics$ ps -o pid,stat,cmd -p $!
    PID STAT CMD
 367529 S    sleep 20
john@trixie:~/debian-handbook/shell-basics$ kill $!
john@trixie:~/debian-handbook/shell-basics$ wait $!; echo nohup_status=$?
[1]+  Terminated              nohup sleep 20 > nohup.out 2>&1
nohup_status=143
john@trixie:~/debian-handbook/shell-basics$ trap 'echo caught-INT' INT
john@trixie:~/debian-handbook/shell-basics$ kill -INT $$
caught-INT
john@trixie:~/debian-handbook/shell-basics$ echo after-kill
after-kill

The transcript's banner is omitted; the session itself is complete. Line by line: sleep 30 & starts the job and immediately prints its job number and process ID - [1] 367524. jobs -l lists the shell's jobs with their process IDs and state. kill %1 sends SIGTERM to job 1; wait %1 waits for it and reports its exit status, and the shell announces the termination when the status is collected. The status 143 is the signal convention from Section 3.2.1: 128 + 15, because SIGTERM is signal 15.

The second job shows how to leave a program running beyond the session. nohup starts a program immune to SIGHUP, the signal a terminal sends when the connection drops; its output is redirected to nohup.out when nothing else is specified, and to whatever redirection you write. $! holds the process ID of the most recent background job, so ps -p $! confirms it is alive and kill $! stops it exactly as before. Without the nohup, a job still running when the shell exits is signaled; an interactive login shell does that only when the huponexit option is set, but a dropped connection closes the terminal regardless. A job can also be removed from the shell's job table with disown when it should survive on its own.

The last pair shows a signal arriving deliberately. trap 'echo caught-INT' INT installs a handler: when SIGINT arrives, the shell runs the quoted command instead of dying. kill -INT $$ sends the signal to the shell itself - $$ is the shell's process ID - and the handler printed its message; without the trap, that signal is what Ctrl+C delivers to the foreground job. kill -l 2 names any signal number:

$ kill -l 2
INT
Job control Effect
cmd & Run cmd as a background job; prints its job number and PID.
Ctrl+C Send SIGINT to the foreground process group.
Ctrl+Z Suspend the foreground job with SIGTSTP.
fg / bg Resume the stopped job in the foreground / background.
jobs -l List jobs with process IDs and states.
kill %N Signal job N; kill -SIG $$ signals the shell itself.
wait Wait for background jobs; $? reports the awaited status.
nohup cmd & Run immune to SIGHUP; output to nohup.out by default.
disown Remove a job from the shell's table.

Leave the session with exit as usual.