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.
What Is Bash (Bourne Again Shell)?
To determine if you are using Bash, open a terminal window and enter the following 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?
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.
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.
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.
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.
A wide range of Bash concepts define how the shell functions and interacts with the user and the system:
|Prompt||The starting point in the CLI where commands are entered. Typically, this indicates the shell is ready to accept a command.|
|Arguments||Additional information provided to a command, specifying how the command should behave.|
|Options/Flags||Special arguments prefixed by |
|Functions||A 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.|
|Wildcards||Characters like |
|Variables||Bash scripts often use variables to store and manipulate data. Variables can hold strings, numbers, or the results of command executions.|
|Expansions||A mechanism where the shell replaces certain tokens with their corresponding values, such as variable expansion |
|Exit Status||A numerical value returned by every command upon its completion, indicating success (|
|Background Jobs||Commands or processes run in the background, allowing the user to continue working.|
|Globbing||The process by which the shell matches filenames based on patterns provided by the user.|
|Interactive vs. Non-interactive Modes||Bash can run in interactive mode (interacting directly with the user) or non-interactive mode (executing scripts).|
|Login vs. Non-login Shells||Login 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:
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.
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:
The script prompts for a name and welcomes the user.
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:
- Concatenate Strings in Bash
- String Comparison in Bash Scripts
- Bash Associative Arrays
- Incrementing and Decrementing Variables in Bash
- Using Single and Double Quotes in Bash Scripts
- The Bash for Loop
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
- ping - Sends ICMP echo requests to a host.
- ifconfig - Displays or modifies network interface configuration.
Archiving and Compression
- grep - Searches for specific patterns in files.
- sed - Stream editor for text manipulation.
- awk - Text processing and data extraction tool.
- 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.
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.