Introduction
Bash is a Unix command line interface for interacting with the operating system, available for Linux and macOS. Bash scripts help group commands to create a program. All instructions that run from the terminal work in Bash scripts as well.Bash scripting is a crucial tool for system administrators and developers. Scripting helps automate repetitive tasks and interact with the OS through custom instruction combinations. The skill is simple to learn and requires only basic terminal commands to get started.This guide will show how to write a Bash script and Bash scripting basics through examples.
Prerequisites
- Access to the terminal (CTRL+ALT+T) with sudo privileges.
- Basic Linux commands (grab our Linux commands cheat sheet).
- A text editor, such as nano or Vi/Vim.
Writing a Bash Script
To start with Bash scripting, create a new file using a text editor. If you're using Vim, run the following command:vim script.sh
The extension for Bash scripts is .sh. However, the extension is not necessary. Adding the .sh makes the file easy to identify and maintain.Adding the "shebang"
The first line in Bash scripts is a character sequence known as the "shebang." The shebang is the program loader's first instruction when executing the file, and the characters indicate which interpreter to run when reading the script.Add the following line to the file to indicate the use of the Bash interpreter:#!/bin/bash
The shebang consists of the following elements:#!
directs the program loader to load an interpreter for the code in the file./bin/bash
the Bash interpreter's location.
Shebang | Interpreter |
---|---|
#!/bin/bash | Bash |
#!/bin/sh | Bourne shell |
#!/usr/bin/env <interpreter> | Uses the env program to locate the interpreter. Use this shebang for other scripting languages, such as Perl, Python, etc. |
#!/usr/bin/pwsh | Powershell |
Note: Learn how to evaluate arithmetic expressions using Bash let.
Adding Comments
Comments are lines that do not execute. However, they help with code readability. After the shebang, add a comment to explain what the script is.For example:#!/bin/bash
# A simple Bash script

Adding Code
As an example, create a script to update and upgrade the system. Add the lines after the Bash comment so the final script looks like the following:#!/bin/bash
# A simple Bash script
sudo apt update -y
sudo apt upgrade -y
echo Done!

Executing the Bash Script
To run the Bash script, use the following command in the terminal:bash script.sh

Note: Learn how to use the Bash read command.