IntroductionBash 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.
- 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 ScriptTo start with Bash scripting, create a new file using a text editor. If you're using Vim, run the following command:
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:
The shebang consists of the following elements:
#!directs the program loader to load an interpreter for the code in the file.
/bin/bashthe Bash interpreter's location.
After adding a shebang, continue to the next section.
|Uses the |
Note: Learn how to evaluate arithmetic expressions using Bash let.
Adding CommentsComments 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:
For more information on Bash comments and the best practices, read our article on how to comment in Bash.
#!/bin/bash # A simple Bash script
Adding CodeAs 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:
The Bash interpreter reads each line and executes the update command followed by the upgrade command. The -y tag automatically answers Yes to any prompt brought up by the two instructions. When completed, the program prints Done! to the console.Save the code and exit the text editor.
#!/bin/bash # A simple Bash script sudo apt update -y sudo apt upgrade -y echo Done!
Executing the Bash ScriptTo run the Bash script, use the following command in the terminal:
The script prompts to enter the password to run the sudo commands. Enter the password and wait for the program to finish the update and upgrade.
Note: Learn how to use the Bash read command.