How to create a bash script in Linux: practical guide

In this guide, we will explore the creating Bash scripts on the operating system Linux. To begin, we will write our first simple script which displays the message “Hello World! First Bash script!” in the console, using the command echo. A Bash script helps automate repetitive tasks, making your workflow easier.

We will also cover how to add arguments to your scripts, which will allow you to automate a wider variety of tasks and interact with the user. As you progress, you will discover advanced techniques to improve your shell scripts.

This tutorial is accessible even to novices, offering them a practical introduction to the use of Bash scripts, while allowing them to gain confidence in their abilities to manipulate the command line of Linux.

The creation of a Bash script on Linux is an essential skill for automating repetitive tasks and improving your productivity. In this article, we’ll explore the steps for writing a simple Bash script, adding arguments, and making your script interactive. With practical examples, you will be able to create your first script and run it efficiently.

The basics of a Bash script

A Bash script is a file containing a series of commands that the Bash shell can execute. To get started, let’s create a script file named hello_world.sh which will display a simple sentence in the console. Here’s how to do it:

Insert the following line into the file:

Then make the file executable:

You can now run the script by typing:

Use arguments in your scripts

Use arguments in your scripts

THE arguments allow you to make a script more flexible. You can adapt the behavior of the script based on the parameters provided. For example, let’s modify our script to accept a name as an argument:

In this example, $1 represents the first argument passed when running the script. To run it, you can do:

The result will be “Hello, Jean!”. This paves the way for creating more complex scripts that respond to various user inputs.

Create an interactive script

It is also possible to render a script interactive by requesting input from the user. We will use the command read for that. Here is an example:

This script will ask the user to enter their name and display it back. This enhances interaction and makes scripts more engaging.

Run and debug your scripts

Run and debug your scripts

To run a script, use the command ./ followed by the file name, as we saw previously. For debugging, Bash provides a useful option:

This will display every command executed, making it easier to identify any errors. This is a valuable practice when developing more elaborate scripts.

Additional Resources

For those who want to learn more about software installation, a helpful tutorial is available here: How to install Node.js on Ubuntu. This can provide additional automation opportunities when you create scripts that interact with other software.