Linux online course

Bash (Bourne Again Shell): Linux Command Interpreter and Core Features

Learn what Bash is, how it differs from a terminal emulator, and how to use commands, pipes, globbing, variables, history, completion, and basic scripts.

Bash is a command-line shell for Linux and other Unix-like systems. It reads commands that you type, interprets their syntax, and either performs shell operations or starts programs supplied by the operating system. Bash is useful both for interactive terminal work and for automation through shell scripts.

What Bash Is

Bash expands to Bourne Again Shell. It is a GNU Project shell written by Brian Fox. Bash was designed as a compatible, enhanced successor to the earlier Bourne shell, commonly called sh.

A shell is a program that provides a command interface. It reads a command line, parses elements such as quoting and wildcards, and then launches a program or performs a built-in shell operation. Bash is widely used as a default login or interactive shell on Linux systems, although the default varies by distribution and can be changed by the user or administrator.

Bash is not the same thing as the window in which you see it. A terminal emulator is the graphical or text application that provides a terminal session. It commonly starts Bash inside that session. The operating system then provides the programs and services that Bash invokes.

ComponentPrimary responsibilityTypical example
Terminal emulatorProvides a window or text session and displays charactersA desktop terminal application
BashReads, parses, and executes shell commandsbash
Operating systemProvides processes, filesystems, devices, and system callsLinux kernel and installed utilities

Starting and Identifying Bash

Opening a terminal commonly starts an interactive shell. The shell displays a command prompt, which is text indicating that it is ready to accept input. The exact prompt is configurable; a prompt ending in $ is a common configuration for a regular user.

bash --version
bash

bash --version displays the installed Bash version. Running bash starts a new interactive Bash process inside the current shell. To leave that nested session, type exit or press Ctrl+D.

echo "$0"
echo "$SHELL"
ps -p $$ -o comm=
  • echo "$0" shows the name associated with the current shell invocation. It is useful evidence, but it is not a guaranteed identification method in every invocation mode.
  • echo "$SHELL" commonly displays the user's configured login shell path. It may not identify the shell currently running in this terminal.
  • ps -p $$ -o comm= asks the process table about the current shell process. $$ is a Bash parameter containing the current shell's process ID.

These distinctions matter because a terminal can launch a shell different from the configured login shell, and a shell can start another shell.

Running Commands Interactively

A command line normally contains a command name followed by zero or more arguments. Arguments provide options or target values. Pressing Enter sends the completed line to Bash.

pwd
ls
ls -l
cd /tmp
pwd
  • pwd prints the current working directory.
  • ls lists directory contents.
  • -l is an option requesting a long listing.
  • cd /tmp uses /tmp as an argument and changes Bash's current directory.

Bash parses the line before execution. Parsing includes recognizing command separators, quotes, variables, wildcard patterns, substitutions, and pipes. The resulting command and arguments are then used to run a Bash built-in or an external program.

Commands generally use three conventional streams: standard input is normal input, standard output is normal results, and standard error is diagnostic output such as error messages. A successful command might write to standard output; a missing file error usually goes to standard error.

pwd && ls -la

The && operator runs the second command only when the first succeeds. This is an example of Bash composing commands.

Filename Expansion and Wildcards

Globbing is Bash's expansion of filename patterns into matching pathnames. A glob is not a regular expression. Bash normally expands the pattern before the command receives its arguments.

PatternMatchesExampleNotes
*Any sequence of characters in a filename component*.txtCan match an empty sequence; normally does not match a leading dot
?Exactly one characterfile?.logMatches file1.log, but not file10.log
[abc]One character listed inside the bracketsfile[abc].txtMatches one of a, b, or c
[a-z]One character in a rangepart[a-z]Range behavior follows the locale and shell rules
printf '%s\n' *.txt
printf '%s\n' file?.log

In a practice directory, the first command prints one matching pathname per line, and the second demonstrates single-character matching. If several names match, Bash passes them as separate arguments to printf.

Pipes and Command Composition

A pipe is the | operator. It connects the standard output of one command to the standard input of the next command. A pipeline is therefore a sequence of separate commands connected by Bash.

ls -1 | sort
printf '%s\n' apple banana apple | sort | uniq

The second example sends text to sort, then sends the sorted text to uniq, which removes adjacent duplicate lines. The pipe carries standard output, not standard error. An error message from an earlier command may still appear directly in the terminal.

When a pipeline behaves unexpectedly, run each stage separately. Check whether the first command produced standard output and whether the next command expects that input format.

Command Substitution

Command substitution captures the standard output of a command and inserts that text into another command line. Prefer the modern $(command) form.

today=$(date +%F)
printf 'Date: %s\n' "$today"

stamp=$(date +%F)
printf '%s\n' "$stamp"

Bash runs date +%F, assigns its output to today or stamp, and then expands the variable. Older scripts may use backticks, such as `date +%F`, but $(...) is easier to read and supports nesting more clearly.

Shell Variables and Environment Variables

A variable is a named value maintained by the shell. Assign it without spaces around the equals sign and reference it with a dollar sign.

project_name='demo files'
printf 'Project: %s\n' "$project_name"

Quotes preserve the value as one argument when it contains spaces or shell-special characters. Double quotes allow variable expansion; single quotes preserve their contents literally.

TypeScope or inheritanceAssignment exampleUse case
Shell variableAvailable in the current shell processname='Ada'Temporary values used by shell commands
Environment variableExported to programs started by that shellexport NAME='Ada'Configuration received by child processes
project_name='sample project'
export PROJECT_NAME="$project_name"
bash -c 'printf "%s\n" "$PROJECT_NAME"'

The child Bash process can read PROJECT_NAME because it was exported. A normal shell variable is not automatically inherited by child processes.

If a variable appears empty, check spelling and capitalization, whether it was exported, whether single quotes prevented expansion, and whether the assignment occurred in a different shell process.

Command History and Editing

Bash records commands entered during interactive sessions. Use the Up and Down arrow keys to recall earlier or later commands, edit the recalled line, and inspect it before pressing Enter.

history

The history command lists numbered entries. Bash can also support history expansion, such as !! for the previous command, but use it cautiously: inspect the expanded command before executing it, especially if it contains a wildcard or a file-modifying operation. History storage, size, and behavior are configurable, commonly through shell settings and startup files.

Tab Completion

Press Tab to complete a partially typed command, directory, or filename. If only one completion is possible, Bash can insert it. If several completions share the prefix, type more characters or press Tab again to list alternatives where completion is configured.

Completion reduces typing and helps avoid filename mistakes. If Tab does nothing, check the spelling and current directory, type a longer prefix, confirm that the cursor is in a position where completion applies, and test with a known existing name.

mkdir completion-practice
cd completion-practice
touch report.txt report.csv README

Type rep followed by Tab for an unambiguous partial match only after you have created or entered the appropriate practice directory. A shared prefix such as re may require another Tab press or more characters.

Common Interactive Features at a Glance

FeatureSyntax or keyWhat it doesBeginner caution
Globbing*.txtExpands a filename pattern into matching pathnamesPreview before modifying or deleting files
Pipelinescommand1 | command2Sends one command's standard output to another's standard inputErrors on standard error do not normally enter the pipe
Command substitution$(command)Inserts command output into another command lineQuote the resulting variable when it should remain one argument
Variablesname=value, $nameStores and expands named valuesAssignment spaces and quoting matter
HistoryUp arrow, historyRecalls and lists earlier commandsInspect recalled commands before running them
Tab completionTabCompletes commands and pathnamesMultiple matches may require more input

Bash for Interactive Work and Scripting

Interactive Bash is suited to direct tasks such as navigating directories, inspecting files, and combining utilities. Bash is also a scripting language. A Bash script is a text file containing shell commands that can be run repeatedly.

#!/usr/bin/env bash
printf 'Hello from Bash\n'

The first line is a shebang, an interpreter directive used when the file is executed directly. The example requests Bash through env. Save it as hello.sh and run it explicitly with:

bash hello.sh

Alternatively, make it executable and run it directly:

chmod +x hello.sh
./hello.sh

Troubleshooting Checklist

  • The prompt or behavior is not Bash-like: run bash explicitly and check bash --version. Distinguish the active shell from the configured value shown by $SHELL.
  • A wildcard selects the wrong files: run pwd, verify the pattern, and preview it with printf '%s\n' pattern. Quoting may have prevented expansion, or no file may match.
  • A variable is empty in a script or child command: check its exact case, use double quotes when expansion is intended, export it when a child process needs it, and remember that separate shell processes do not share ordinary variables.
  • A pipeline has no output: run every stage separately. The first command may produce no standard output, the next command may expect another format, or the visible diagnostic may have gone to standard error.
  • Tab completion fails: verify the directory and spelling, type more of the name, press Tab again to list alternatives when supported, and try a known existing filename.

Key Points

  • Bash is both a command interpreter and a scripting language.
  • The terminal emulator provides the session; Bash interprets commands inside it.
  • Bash parses command lines before launching programs or applying shell operations.
  • Globbing expands filename patterns, while pipes connect command streams.
  • Command substitution captures output, and variables store values for later expansion.
  • History and Tab completion make interactive work faster, but recalled or expanded commands should be inspected before execution.
  • Exported variables reach child processes; ordinary shell variables normally do not.
  • Bash scripts can be run with bash scriptname or through an executable shebang.

For related command-line study, see Linux and Show the Full Path of Shell Commands.