WindowsMacSoftwareSettingsSecurityProductivityLinuxAndroidPerformanceConfigurationApple All

How to Write Bash Scripts on Linux

Edited 2 days ago by ExtremeHow Editorial Team

Shell ScriptingAutomationCommand LineProgrammingScriptingSysAdminUtilitiesBeginnersProductivitySoftware Development

How to Write Bash Scripts on Linux

This content is available in 7 different language

Bash scripting is a vital skill for anyone who wants to use Linux to its full potential. Whether automating system tasks, manipulating files, or handling complex work operations, Bash scripts make life easier. In this guide, we will explore how to write Bash scripts in Linux, which is meant for both newbies and those who need a refresher. It will provide insight into the basic aspects, as well as practical examples to illustrate key concepts.

What is bash?

Bash, or the Bourne Again Shell, is a command processor that runs in a text window where users can enter commands to be executed by the operating system. Created as a free software replacement for the Bourne shell, Bash is a powerful tool that comes with lots of built-in functions to speed up the world's technology.

Prerequisites

Before writing a Bash script, it is important to make sure you have a Linux-based operating system installed. Almost all Linux distributions come with Bash pre-installed, as it is the default command-line interpreter for most Unix systems.

Understanding bash scripts

A bash script is simply a text file that contains a series of commands. It is often used to automate operations on your computer and works in conjunction with the Linux operating system. Bash scripts are extremely powerful, and they can save time by automating complex batch processing tasks.

Basic steps of writing a bash script

Follow these simple steps to start writing Bash scripts:

1. Create new file

Start by creating a new file. You can use the touch command to create a file:

touch scriptname.sh

Alternatively, you can create the file directly from a text editor like nano:

nano scriptname.sh

2. Add the shebang

The shebang is the first line in any bash script. It tells the system which interpreter to use to parse the rest of the script. For bash, it typically looks like this:

#!/bin/bash

3. Write your script

Below the shebang line, you begin writing your code. Let's write a basic script that prints "Hello, World!" to the terminal.

#!/bin/bash
echo 'Hello, World!'

4. Save and close the file

If you're using nano, you can save your file by pressing CTRL + O, and then exit using CTRL + X.

5. Make the script executable

Before you can run your script, it must be executable. To do this, use chmod:

chmod +x scriptname.sh

6. Run the script

Once the file is executable, you can run it by typing:

./scriptname.sh

Understanding bash commands

Bash scripts are made up of various commands. Below are some commonly used bash commands:

Variables in bash scripts

Variables store data that can change. Unlike other programming languages, Bash variables do not require a type; any string or number can be stored in a variable.

Setting the variables is easy:

variable_name='value'

To access the value stored in a variable, place the dollar sign $ in front of the variable name, as shown:

echo $variable_name

Comments in bash

Comments are used to describe or explain the code in your script. This can be very helpful when you're revisiting your code or when other people are reading it.

Single-line comments begin with the hash # symbol:

# This is a single line comment

Conditions in bash script

Conditional expressions are used to make decisions, and these expressions can compare numbers, strings, or return conditions of commands.

The basic conditional syntax for if-else statements is as follows:

if [ condition ]; then
    # commands to execute if condition is true
else
    # commands to execute if condition is false
fi

Loops in bash scripts

Loops provide the ability to repeat tasks. The most common loops are for loops and while loops.

For loop

The for loop iterates over the list of items and executes code for each item:

for item in item1 item2 item3; do
    echo $item
done

While loop

The while loop continues until the specified condition is false:

while [ condition ]; do
    # commands to execute
done

Functions in bash scripts

Functions allow you to group commands in a script into sections that you can call repeatedly. This can help make your script more organized and reduce repetition:

function_name() {
    # commands to execute
}

Call the function by simply referring to its name:

function_name

Passing arguments to a bash script

Bash scripts can accept input parameters from the command line. These parameters are stored in the variables $1, $2, $3, etc., with $0 representing the name of the script:

echo "The first argument is: $1"

Using external commands

Bash allows you to use external system commands within your scripts, such as:

result=$(ls -l)
echo "$result"

Creating a simple backup script example

Let's create a simple bash script to back up a directory:

#!/bin/bash
src="/path/to/source"
dest="/path/to/destination"
tar -czf backup-$(date +%Y-%m-%d).tar.gz -C "$src" .
mv backup-$(date +%Y-%m-%d).tar.gz "$dest"

This script compresses the contents of the source directory and moves the archive to the destination location.

Bash script debugging

Debugging is important when things don't go as planned. Bash provides options for debugging scripts:

  1. Using the -x option: To see what your script is doing, you can run it with the -x option:
bash -x scriptname.sh

Best practices

Conclusion

Writing Bash scripts on Linux is a powerful skill that can help automate daily tasks, manage system activities, and even handle complex processes. Whether you're just starting out or looking to hone your scripting abilities, the above guide provides a strong starting point. By following these steps and adhering to best practices, you can become proficient at writing your own Bash scripts and take advantage of the full range of functionality Linux has to offer. Like any skill, practice will improve your ability, and over time you'll be able to create scripts to handle increasingly complex tasks.

If you find anything wrong with the article content, you can


Comments