Bash Scripting
Learn Bash scripting with our in-depth course, or jump in to a topic of your choosing!
Bash Scripting Tutorials
Introduction to Bash Scripting
Variables in Bash
— Special Variables
Numbers in Bash
Math in Bash
Bash Operators
— Operator Reference
Working With Input
Bash Functions
Bash Script Examples
Bash Script to Generate a List of Numbers
What is Bash Scripting?
In the world of Linux and Unix-like operating systems, ‘bash scripting‘ refers to creating a text file or a ‘one-liner’ containing a series of commands that Bash (bourne-again shell) can execute.
Bash scripting is a powerful tool for automating tasks, simplifying complex operations, and improving productivity.
Whether you’re a system or network administrator, developer, or just a curious enthusiast, learning Bash scripting can open up a world of possibilities.
Our guide is designed for beginners who are new to Bash scripting. In this article, we’ll cover the Bourne-again shell (Bash) and bash scripting at a high level. We’ll also see a practical example to help you get familiar with bash scripts.
Looking ahead: After this topic, we’ll be ready to cover the essentials to bash scripting: variables, loops, conditionals, and functions. As we progress, we’ll explore more advanced topics like command-line arguments, input/output redirection, and error handling. By the end of this guide, you’ll have a solid understanding of Bash scripting fundamentals and the confidence to start writing your own scripts. So, grab your favorite text editor, fire up your terminal, and let’s dive into the world of Bash scripting!
What is a Bash Script?
A Bash script is a file containing a series of commands that the bourne-again shell, commonly known as Bash, can execute.
The bourne-again shell (Bash) is not just a command interpreter, but is also a full-fledged programming environment. This means that we can use things like conditional expressions and loops to guide control flow. Bash also makes it easy to work with user input and display output to the console.
At its’ core, a bash script is just a text file. Bash scripts commonly use the .sh file extension, but this isn’t mandatory. However, the user executing the script must have permissions to do so. We’ll see how to do this below.
Remember: Bash isn’t just a command-line interpreter. It’s a complete programming language.
Introducing the Bourne-Again Shell (Bash)
The Bourne-Again Shell, abbreviated as Bash, is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell (sh).
Bash has become the default shell for most Linux distributions and macOS. As a result, it’s widely used on Unix-like operating systems.
Bash offers features such as command-line editing, history substitution, customizable prompts, job control, and shell scripting capabilities. It’s highly versatile and powerful, making it a popular choice for both interactive use by users and for scripting purposes.
Bash Script vs. One-Liner
Bash scripts are often compared with one-liners. Both are sequences of Bash commands, but there are some differences – both in terms of what they are, as well as when they are used.
Scripts and one-liners are both very useful. Many people develop their own personal guidelines or rules for when to use a script vs. a one-liner, such as based on length, complexity, and convenience.
The key difference between Bash scripts and one-liners is that a script is a file, while a one-liner is a set of commands entered directly into the Bash command line. By nature, a Bash script can handle more complicated tasks than a one-liner. One-liners are often used for quick tasks or when you want to execute a command without creating a separate script.
In general, it’s a good idea to use a Bash script whenever we need to perform multiple tasks, manage variables, or use control structures like loops and conditionals. Scripts are also useful for tasks that need to be repeated or for organizing and documenting your code.
One-liners are more suitable for simple tasks that can be accomplished with a single command or a short sequence of commands. They are convenient for executing commands quickly in a terminal or combining multiple commands in a concise fashion. However, one-liners can become complex and hard to read if they are too long or contain multiple commands, so it’s a good idea to use them judiciously.
Sometimes one-liners may actually be a sequence of commands run directly on the command line, rather than actually being on a single line. The key point is that the difference between a one-liner and a script is that the script is saved into a file.
As mentioned, developers often decide for themselves the criteria for when to write a sequence of commands as a one-liner vs. a script. Common criteria include:
- Reuse: If a set of commands is to be reused often, it is common to save them into a file as a script.
- Complexity: A sufficiently complex series of commands necessitates use of a script.
- Comments: It can be helpful to include comments in the code, which again necessitates a script.
- Readability: Scripts are generally more readable. Having each command on a line, indentation, and other factors can make a script more readable than a one-liner.
This isn’t to say that one-liners aren’t incredibly useful! One liners are perfect when the code is simple, doesn’t need to be reused, and won’t be significantly benefited by comments or improved readability.
A “Hello, World!” Bash Script
Let’s take a look at a simple “Hello, World!” Bash script, which can teach us a great deal.
#!/bin/bash
# This is a comment in Bash!
echo "Hello, World!"
The first line of the script typically starts with `#!` – called a shebang, followed by the path to the Bash interpreter. For example, `#!/bin/bash`. The shebang line line tells the system which interpreter to use to execute the script.
The second line is a comment. It is ignored by the compiler and does not get executed. Comments are useful for adding documentation to code.
Finally, the third line executes the echo command, which prints the string “Hello World!” to the console.
Saving and File Permissions
The script above can be saved into a file using a text editor of your choice. On Linux, vim and nano are fine options but GUI editors are great as well.
Before you can execute the script, you need to ensure it has the ‘execute’ permission set. You can do this with the `chmod` (change mode) command in a terminal:
chmod +x script.sh
In this example, the ‘+x’ flag gives execute permissions over the script.sh file.
Executing a Bash Script
Once the script is saved and permissions are set, it can be executed in one of the following ways:
bash script.sh
./script.sh
If the script takes any arguments, they will be provided following the script name:
bash script.sh <argument 1> <argument 2>
./script.sh <argument 1> <argument 2>
When we run a Bash script in Linux, the operating system interprets the script using the Bash shell.
The Bash interpreter reads the script line by line, executing each command in order. It starts at the top of the file and proceeds sequentially unless directed otherwise by control flow statements like loops or conditionals.
After the script finishes executing, it returns an exit status to the shell. This status indicates whether the script ran successfully (`0` for success) or encountered an error (`non-zero` for failure).
A Practical Example of Bash Scripting
Here’s a slightly more complex example of a Bash script that takes user input and performs some basic operations:
#!/bin/bash
# This script calculates the area of a rectangle
# Prompt the user for the length and width of the rectangle
echo "Enter the length of the rectangle:"
read length
echo "Enter the width of the rectangle:"
read width
# Calculate the area
area=$((length * width))
# Display the result
echo "The area of the rectangle with length $length and width $width is: $area"
Save this script in a file (e.g., `area.sh`), make it executable with `chmod +x calculate_area.sh`, and then run it with `./area.sh`.
It will prompt you to enter the length and width of a rectangle, calculate the area, and then display the result.
This script demonstrates a few additional concepts:
- The `read` command is used to read user input.
- Variables (`length`, `width`, `area`) are used to store and manipulate data. – The `echo` command is used to display the result to the user.
- Arithmetic operations in Bash are performed using the `$( … )` syntax.
We’ll cover each of these in greater detail during this course. If the above example seems confusing to you, don’t fret. Read it a few times and give yourself time to learn a new language. You’ll be a pro at Bash before you know it!