Linux Tutorial / How the Shell Runs Commands: ;, &&, ||, Aliases, and Environment Variables

Bash reads a command, resolves its name and arguments, performs expansions and redirections, and then runs it. A semicolon ; runs the next command regardless of the previous result, && runs it only after success, and || runs it only after a nonzero status. Aliases change command text as the shell reads it; environment variables pass settings to child processes. These distinctions explain why similar-looking command lines can behave differently.

Start with variables, environment variables, aliases, exit status, and basic &&/|| flow. Command groups, pipelines, background work, and the complete script are optional deeper reading. The first Bash script turns these rules into a file; Bash error handling develops failure, path, and concurrency limits.

How is a command name resolved?

The examples assume Bash. The shell reads the command line, handles arguments, variables, and redirections, and resolves the command name. An alias, function, shell built-in, or executable found through PATH can produce different behavior. Inspect the current shell's resolution with:

type -a printf
type -a ls
command -v ls

type -a can show aliases, functions, built-ins, and executable candidates. command -v checks whether a name can be resolved. PATH lists directories searched for external executables; it does not explain every alias or function as one file path. Do not overwrite your system's PATH for this exercise.

Read exit status and execution symbols

A command leaves an exit status. Zero indicates success; a nonzero value indicates failure or another outcome defined by the command. For example, grep can return 1 when nothing matches. Read $? immediately, or save it in a variable, because another command replaces the most recent status.

true
printf 'status=%s\n' "$?"
false
printf 'status=%s\n' "$?"

The output is status=0, followed by status=1. Conditional execution uses the status, not whether a message looks successful. Bash returns 127 for a command it cannot find and 126 for a command it finds but cannot execute. Signal termination has its own status convention; do not assume every failure returns 1.

Symbol Purpose
; Run the next command regardless of success or failure
&& Run the next command only after success
|| Run the next command only after a nonzero status
& Run asynchronously without waiting
| Connect standard output to the next standard input
|& Pipe both standard output and standard error
! Logically invert the status of a command or pipeline

The Bash lists documentation classifies ;, &, &&, and || as list operators. | and |& form pipelines, while ! is a reserved word that negates a pipeline status. Run these examples in Bash with true, false, printf, grep, cat, and sleep, normally available on Ubuntu and Rocky Linux. No administrative privileges are needed.

Connect commands according to success or failure

Separate sequencing from conditional execution

; waits for the preceding command and then continues regardless of its result. A newline also separates commands in ordinary lists. Quoting, backslashes, pipelines, or incomplete compound commands can make Bash continue reading instead of treating the newline as the end of a command.

false; printf 'always\n'
false && printf 'not run\n'
false || printf 'fallback\n'
true && printf 'next step\n'

The output is always, fallback, then next step; not run is skipped. && and || use short-circuit evaluation: the right side is skipped when its condition is not met. The pattern cd /actual/work/path && work_command prevents a failed directory change from running the work in the wrong directory. Replace that illustrative path and command with real, prepared values.

Distinguish evaluation order from an if branch

&& and || have equal precedence and associate from left to right. In A && B || C, C can run even when A succeeds, because B can fail.

true && false || printf 'fallback runs\n'

This prints fallback runs. Use if when only the original condition should select one of two branches.

if true; then
  false
else
  printf 'condition failed\n'
fi

There is no output: the failing false inside the selected then branch does not switch execution into else. That failure still needs deliberate handling in a production script; choosing the right branch does not recover failed work.

Report a failure without losing its meaning

false || printf 'failure reported\n'
printf 'list status=%s\n' "$?"

The output is failure reported, then list status=0. || does not inherently mean “ignore errors,” but the successful printf becomes the last executed command and gives the list a zero status. Save and return the original failure with exit when the script must fail after reporting it.

Group commands into one unit

Braces run in the current shell

{ ...; } groups commands in the current shell. Separate the braces from the commands with whitespace, and put a semicolon or newline before the closing brace.

LESSON_SCOPE=outer
{ LESSON_SCOPE=inner; printf '%s\n' "$LESSON_SCOPE"; }
printf '%s\n' "$LESSON_SCOPE"
unset LESSON_SCOPE

This prints inner twice because the variable change remains in the current shell. The final unset removes the practice variable.

Parentheses use a subshell

LESSON_SCOPE=outer
( LESSON_SCOPE=inner; printf '%s\n' "$LESSON_SCOPE" )
printf '%s\n' "$LESSON_SCOPE"
unset LESSON_SCOPE

This prints inner, then outer. Parentheses create a subshell environment, so ordinary variable assignments and directory changes do not remain in the outer shell. This does not undo external effects such as file changes or service requests. See Bash command grouping for the distinction.

Use pipes, standard error, and status inversion

Distinguish a pipe from a condition

printf 'alpha\nbeta\n' | grep 'alpha'

Only alpha is printed. | connects the preceding standard output to the next standard input. It does not select a command after failure as || does. Pipeline commands process connected streams; they are not a sequence of success-gated steps.

Include standard error with |&

bash -c 'printf "normal\n"; printf "error\n" >&2' |& cat

Both normal and error pass through cat. In this example, Bash |& combines standard error with standard output like 2>&1 |. When other redirections are present, their ordering matters; do not replace syntax blindly. A downstream tee can display and log the stream, but the two kinds of output have then been combined.

! negates status rather than output

! false
printf 'inverted status=%s\n' "$?"

This prints inverted status=0: the failing false is negated into success for condition testing. An original zero status becomes nonzero. Output text and file contents are not inverted.

Check pipeline failures with pipefail

( set +o pipefail; false | cat; printf 'default=%s\n' "$?" )
( set -o pipefail; false | cat; printf 'pipefail=%s\n' "$?" )

The output is default=0, then pipefail=1. A pipeline normally returns the last command’s status, so a successful cat can conceal the preceding false. With pipefail, the status is zero only when all commands succeed; otherwise it comes from the rightmost failing command. Parentheses isolate both comparisons so they do not change the outer shell’s options. The Bash pipelines documentation describes these rules.

Start a background job and check completion

& starts asynchronous execution without waiting for completion. It differs from &&, which proceeds only after success. This example starts a short background job and then deliberately waits for its completion.

sleep 2 &
lesson_job=$!
printf 'foreground continues\n'
wait "$lesson_job"
printf 'job status=%s\n' "$?"
unset lesson_job

foreground continues appears first, followed by job status=0 after completion. $! identifies the most recent background process. The immediate $? after starting it does not establish whether the job ultimately succeeded. Interactive Bash provides jobs, fg, and bg to inspect and move jobs. Appending & alone does not guarantee survival after logout; choose suitable session or service management for long-running work.

Practice the flow with a complete script

The complete example below simulates build, test, and deployment with messages. It performs no actual build, deployment, or file deletion. Save it as a new file named course15-flow.sh in an empty practice directory. Only Bash is required; you do not need to make the file executable.

#!/usr/bin/env bash
build() { printf 'build\n'; }
run_tests() { printf 'test\n'; return "${1:-0}"; }
deploy() { printf 'deploy\n'; }

build && run_tests "${1:-0}" && deploy
lesson_status=$?
if (( lesson_status != 0 )); then
  printf 'workflow failed: status=%s\n' "$lesson_status" >&2
fi
exit "$lesson_status"
bash course15-flow.sh 0
echo $?
bash course15-flow.sh 1
echo $?

The first run prints build, test, and deploy, then returns 0. Changing the argument to 1 prints only build and test, reports the failure on standard error, and returns 1. Run it with 0 again to restore the successful path. ${1:-0} uses zero when the first argument is missing or empty; use only zero or one for this exercise.

A function defined with name() { ...; } names a command group; return supplies its status. Saving the workflow status immediately in lesson_status prevents the reporting message from replacing the original failure. In real operations, substitute prepared, validated tasks and handle each failure explicitly.

Use semicolons for short independent steps, && for success-dependent work, and if plus functions for branching and recovery. work; cleanup runs cleanup after an ordinary work failure, but does not guarantee it when the shell exits early or receives a signal. Design such cleanup with facilities such as trap. Likewise, set -e does not automatically handle every error: conditions and AND/OR lists have exceptions, so inspect important statuses explicitly.

Aliases expand when Bash reads a command

alias creates a short command name commonly used in interactive Bash. Enter the following definition, then run ll or type ll at a new prompt. Bash reads and parses commands before executing them, so defining and using an alias in the same compound command may not expand as expected.

alias ll='ls -l'
type ll
ll

An alias normally affects only the current shell and is not expanded in noninteractive Bash unless enabled separately. Do not make an automation script depend on an interactive alias by accident. Remove this practice alias with unalias ll. For reusable operations needing arguments, consider a shell function rather than an alias.

Distinguish shell variables from the environment

A shell variable is available in the current shell. Once exported, it is also placed in the environment of subsequently launched child processes. Use a practice-only name rather than a common system variable:

LESSON_MODE=practice
printf '%s\n' "$LESSON_MODE"
export LESSON_MODE
printenv LESSON_MODE

Both outputs are practice. The first comes from expansion in the current shell; the second is read from the environment passed to the external printenv process. Exporting does not retroactively change an already-running other shell or a parent process.

To supply a value for one command only, use NAME=value command. When finished, run unset LESSON_MODE in the current shell. Do not repurpose your home-directory or system PATH variable as a practice name.

Troubleshoot execution order

  • If you do not know how a name resolves, begin with type -a name.
  • If conditional execution surprises you, examine each stage's exit status separately.
  • If an alias fails, check that Bash is interactive and that you used it on a new command line after defining it.
  • If a child command cannot see a variable, check whether it was exported.

Sequencing operators, aliases, and variables all affect execution, but they are not interchangeable. Before connecting commands that change files, test the flow with low-impact built-ins such as true, false, and printf.

Official documentation

The GNU Bash lists documentation covers ;, &&, and ||. The Bash aliases documentation covers expansion timing. For variables and environment behavior, see the Bash Reference Manual.

For detailed rules, consult the GNU Bash documentation on pipelines and pipefail, command grouping, and exit status.