What Is Bash?

September 14, 2023

Introduction

For decades, Bash (Bourne Again SHell) has been the primary interface in UNIX-based systems. It is a versatile and customizable shell, packed with features that allow casual users, programmers, and system administrators to use the command line effectively.

This article introduces Bash, explores its functions and features, and explains why it remains relevant even in the age of modern graphical interfaces.

User exploring Bash commands and concepts.

What Is Bash (Bourne Again Shell)?

Bash is a shell program that provides an environment for users to issue commands and run other applications. When you open a terminal in most Linux distributions, you use the Bash shell by default.

Users can type commands in the Bash command-line interface (CLI) to navigate files, manage processes, install software, and perform almost any operation the operating system supports.

To determine if you are using Bash, open a terminal window and enter the following command:

echo $0
Check bash shell with echo command.

The system responds with bash, indicating that the Bash shell is running.

Bash is also a scripting language, which means users can create a script that contains multiple Bash commands to be executed in a specific sequence. These are the same commands users enter manually in the terminal. Bash scripts automate repetitive tasks, streamline complex operations, and create new tools and utilities.

Note: Bash scripts are portable and work on any system with Bash installed.

What Is a Shell?

A shell is a user interface that interprets user commands into actions the operating system can perform. These actions include managing files, interacting with hardware, or launching applications.

There are two predominant types of shells:

  • Command-line shells. This shell type provides a command-line interface to the operating system. Users input commands into the terminal, which the shell then processes. Popular command-line shells include Bash, Zsh, Tcsh, Fish, and KornShell.
  • Graphical shells. Users interact with the system through a graphical interface (GUI) via icons, buttons, and windows. A mouse or keyboard shortcut is used to initiate the interactions. Examples of graphical shells include the Windows shell, the GNOME Shell (part of the GNOME desktop environment), and the macOS Finder interface.

Most shells also offer a programming environment that allows users to write scripts and handle tasks programmatically.

Short Bash History

Some solutions, like Bash, have become so embedded within a technological ecosystem that it's easy to forget they were invented.

Brian Fox developed Bash in 1989 for the GNU Project as a free software successor to the Bourne shell (sh). The name Bourne Again Shell was meant to signify that Bash was a new and improved version of sh. Bash builds on sh and introduces additional features not found in the original Bourne shell, which include:

  • Job control.
  • Command history.
  • Shell functions and aliases.
  • Command-line editing and completion.
  • Conditional commands (bash if and bash case statements).
  • Basic debugging and signal handling.
  • Indexed arrays with no size limitation.
  • Support for HereDocs.

Its adoption across Linux distributions solidified its position as the go-to shell in UNIX-like operating systems.

Note: Bash was the default shell on macOS until the introduction of macOS Catalina, when the Zsh shell replaced it. However, Bash is still available on macOS, and you can change zsh back to bash if required.

Shell development history.

Since its launch, Bash has undergone several iterations, introducing new features and improvements. Chet Ramey took over the development in the late 1980s and continues to maintain Bash.

What Is Bash Used For?

IT professionals use Bash extensively to complete a varied array of tasks, including:

  • Executing Commands. The Bash command-line interface allows users to control running processes, navigate the file system, launch applications, and manage files and directories.
  • Scripting. Programmers write Bash scripts and execute command sequences to automate workflows and create new tools and features.
  • Piping and Data Processing. Bash supports using the pipeline (|) character to pipe the output of one command into another, allowing a chain of operations to be applied to data sequentially. For example, data scientists and analysts can use Bash pipelines for quick data wrangling.
  • Customization and Environment Setup. Configuration files like .bashrc and .bash_profile enable users to customize the Bash environment and set up aliases, environment variables, and prompts.
  • Task Scheduling. Bash scripts can be scheduled to run at specific times or intervals. For example, database admins use Bash to schedule backups or optimize databases during off-peak times.
  • Programming and Development. Developers use Bash to compile and run software, manage project dependencies, or automate development workflows.
  • System Administration. System administrators use Bash to configure services, monitor resources, deploy applications, and complete related system management tasks.
  • Networking. Network administrators use commands like ssh and netstat to facilitate data transfers and remote system management.
  • Interactive Workflows. Bash can prompt users for input, which is practical for creating guided workflows. For example, helpdesk technicians can develop guided workflows for troubleshooting common problems instead of personally walking an end-user through a process.

How Does Bash Work?

Like other shells, Bash operates as an interface between the user and the underlying operating system, specifically the kernel. The following is a high-level overview of how Bash works:

1. Initialization. When Bash starts, it reads and executes initialization scripts, like .bashrc for individual users or /etc/profile for system-wide configurations. These scripts define the Bash environment, its functions, and customize the behavior of the shell.

2. Command Prompt. After initialization, Bash displays a prompt and waits for the user to enter a command.

3. Command Reading. The user types a command in the prompt and presses Enter. Bash proceeds to read the command.

4. Command Parsing. Bash breaks the command into words and tokens. It identifies command names, arguments, operators, and redirection symbols.

5. Expansion. If the command contains brace, variable, or pathname expansions, Bash will modify or extend the original command based on patterns or outputs of other commands.

Diagram displays how Bash works.

6. Command Execution. Bash determines if the command is built-in, external, or a function and then executes the command or launches the appropriate program.

7. Redirection and Piping. Bash handles any redirections, where command output goes, or where input comes from. It also handles piping operations by sending the output of one command as the input to another.

8. Job Control. Bash can manage multiple tasks (jobs) simultaneously, allowing users to pause, control, and terminate background or foreground tasks using bg and fg Bash commands.

9. Repeat. After executing a command, Bash returns to step 2, presenting the user with another prompt and waiting for the following command.

10. Termination. When the user types exit or presses CTRL+D to exit the shell, Bash will terminate background processes and execute termination scripts before closing.

During this process, Bash interacts with the kernel through system calls to perform the necessary action.

Bash Features

Some of the more notable Bash features include:

  • Built-in Commands. Bash has numerous built-in commands, such as cd, echo, and pwd, that execute directly within the shell without invoking external binaries.
  • Command History. Bash keeps a history of user commands, allowing them to be recalled and rerun.
  • Command-line Editing. Users can navigate and edit commands using shortcuts that are in the style of those used in vim.
  • Auto-completion. Pressing the Tab key automatically fills in or suggests command names, filenames, directory names, or other relevant data based on the context and the characters entered initially.
  • Aliases. Bash supports user-defined shortcuts for longer commands or sequences of commands.
  • Shell Scripting. Users can utilize Bash commands and create scripts that include variables, functions, conditional statements, and loops to support various automation options.
  • Redirection. Directing the input and output of commands to files or devices using directional operators like >, >>, and <.
  • Piping. The pipe (|) operator enables users to utilize the output of one command as input for another command.
  • Variables and Environment. Users can configure local and environment variables, like $PATH or $HOME, to modify settings for the shell and associated programs.
  • Arithmetic Evaluation. Bash can perform arithmetic operations directly within the shell using the $((expression)) syntax.
  • Interactive Features. The Bash shell can interact with users and prompt them for input during script or command execution. It is possible to customize Bash prompts for a better user experience.
  • Extensibility. Bash allows users to create custom commands and functions, extending its capabilities.
  • Networking. Networking tools like curl and scp can be effectively used in scripts and command sequences.

Bash Concepts

A wide range of Bash concepts define how the shell functions and interacts with the user and the system:

Bash ConceptsDescription
PromptThe starting point in the CLI where commands are entered. Typically, this indicates the shell is ready to accept a command.
ArgumentsAdditional information provided to a command, specifying how the command should behave.
Options/FlagsSpecial arguments prefixed by - or -- that modify the behavior of a command.
FunctionsA Bash function groups reusable portions of code under one name to be reused later. Functions are similar to scripts but are defined and executed within the environment.
WildcardsCharacters like *, ?, or [] are used to represent or match filenames or strings based on patterns.
VariablesBash scripts often use variables to store and manipulate data. Variables can hold strings, numbers, or the results of command executions.
ExpansionsA mechanism where the shell replaces certain tokens with their corresponding values, such as variable expansion $VARNAME, command substitution $(command), or brace expansion {1..100}.
Exit StatusA numerical value returned by every command upon its completion, indicating success (0) or various types of errors (non-zero).
Background JobsCommands or processes run in the background, allowing the user to continue working.
GlobbingThe process by which the shell matches filenames based on patterns provided by the user.
Interactive vs. Non-interactive ModesBash can run in interactive mode (interacting directly with the user) or non-interactive mode (executing scripts).
Login vs. Non-login ShellsLogin shells (started when a user logs in) and non-login shells source different configuration files.

What Is Bash Scripting?

A Bash script is a text file that contains a series of Bash commands. When the script is executed, the Bash shell reads and processes these commands sequentially.

Bash scripts extend the capabilities of Bash from simply executing commands interactively in a terminal to chaining commands together in sophisticated ways, executing conditional logic, and looping over sequences of values.

Follow the steps below to create a simple Bash script:

1. Access the terminal and use a text editor to create a plain text file. In this example, the nano text editor is used to create a script called test_script.sh:

nano test_script.sh

A Bash script starts with a character sequence called a shebang (#!), followed by the path to the Bash executable. This tells the system that this script should be executed using the Bash shell.

Note: Like other programming languages, the # character is used to comment in Bash scripts.

2. Copy and paste the following code in the test_script.sh file:

#!/bin/bash

# Prompt the user for input
echo "Please enter your name:"

# Read the user's input into a variable called 'username'
read username

# Print a greeting
echo "Hello, $username! Welcome to the Bash world."

The commands in the test_script.sh script instructs Bash to:

  • Prompt the user for a name.
  • Store the name the user enters as a variable called username.
  • Print a greeting using the username variable.
Simple bash script.

3. Save the file and exit the editor.

4. Enter the following command to make the script executable:

chmod +x test_script.sh

Note: Did you know there are 7 different ways to run Bash scripts, and this is just one of them?

5. Enter the following command to run the script:

./test_script.sh

The script prompts for a name and welcomes the user.

Bash prompt based on script.

The script above is a straightforward example of a Bash script. Bash scripts support advanced programming mechanisms like conditionals, reusable blocks, and associative arrays. Tap into many of these advanced Bash scripting features by reading our detailed guides:

25 Common Bash Commands

Knowledge of Bash commands and concepts is fundamental to writing effective scripts. The following list contains 25 frequently used Bash commands:

File and Directory Operations

  • ls - Lists directory contents.
  • cp - Copies files or directories.
  • rm - Removes files or directories.
  • cat - Concatenates and displays file content.
  • mkdir - Creates a directory.
  • rmdir - Removes a directory.

Permissions and Ownership

  • chown - Changes file owner and group.
  • chgrp - Changes file group.

Process Management

  • top - Displays real-time processes.
  • kill - Sends signals to processes (commonly used to terminate).

Networking

  • ping - Sends ICMP echo requests to a host.
  • ifconfig - Displays or modifies network interface configuration.

Archiving and Compression

  • tar - Creates or extracts from archive files.
  • gzip & gunzip - Compresses and decompresses files.

Text Processing

  • grep - Searches for specific patterns in files.
  • sed - Stream editor for text manipulation.
  • awk - Text processing and data extraction tool.

Misc

  • alias - Creates command shortcuts.
  • history - Shows command history.
  • eval - Executes dynamic commands in strings or variables.
  • read - Reads text from standard input.
  • find - Searches for files in a directory hierarchy.
  • let - Evaluate arithmetic expressions.
  • trap - Exit scripts predictably.
  • wait - Instructs Bash to wait for background processes to finish before exiting the shell.

This list contains only a fraction of the commands, tools, and utilities Bash and the larger UNIX ecosystem offer. Read our detailed article on the essential Bash commands and download a convenient Bash Commands Cheat Sheet for quick reference.

Conclusion

After reading this article, you will know how Bash works, its origins and features, and its underlying concepts.

When you launch a terminal on your Linux system, Bash is your interface. While it's great for handling simple commands, more importantly, it is a gateway for automating repetitive tasks and streamlining operations.

Was this article helpful?
YesNo
Vladimir Kaplarevic
Vladimir is a resident Tech Writer at phoenixNAP. He has more than 7 years of experience in implementing e-commerce and online payment solutions with various global IT services providers. His articles aim to instill a passion for innovative technologies in others by providing practical advice and using an engaging writing style.
Next you should read
How to Redirect stdout and stderr to File in Bash
August 30, 2023

Find out how I/O streams work and why they help you understand redirections even better. In this article, you'll learn how to redirect stdout/stderr to a file in Bash.
Read more
Bash declare Statement: Syntax and Examples
December 23, 2021

Although the built-in declare statement does not need to be used to explicitly declare a variable in bash, the command is often employed for more advanced...
Read more
Linux Network Commands Cheat Sheet
September 13, 2023

Master Linux networking commands! This article provides an overview of 20 Linux network commands, and features a free downloadable PDF cheat sheet.
Read more
CLI vs. GUI: What Are the Differences?
February 1, 2023

The CLI and GUI both serve the same purpose of facilitating the users' interaction with the OS. Read this article to learn the key differences between the two UIs.
Read more