Articles

Creating a Bash Script in Linux

Creating a Bash Script in Linux

Linux Operating System

11/10/2023 14:10

Serhat P.

20 min. reading

Ready to create your own automated tasks and customised commands? Discover the power of Bash scripting now and increase your productivity on Linux!

Introduction to Bash scripting

Bash is a shell program frequently used in Linux and UNIX based operating systems. While it usually allows individual commands to be executed from the command line, it also has the ability to run scripts, which are a collection of commands. Bash scripting is an excellent tool for performing automated tasks, customised commands and more complex workflows. These files contain a series of Bash commands in a specific order and logic and are usually saved with the '.sh' extension. They can be created using a simple text editor and must be equipped with the appropriate permissions before being executed. Learning the basics of Bash scripting can significantly increase your productivity and automation capacity in Linux.

Understand the basics of Bash scripting

A Bash script, as its name implies, is a set of commands written to be executed in the Bash shell. At the very beginning of a script is a shebang line '#!/bin/bash', which specifies the interpreter with which the script is to be run.

The basics of a Bash script include the following:

  • Commands: Bash scripts consist of a series of commands. Commands are programs in the Linux operating system that perform various operations. For example, the echo command prints a text message.
  • Descriptions: Comments are used to explain what the script does. Comments are also known as comment lines and start with a # sign.
  • Variables: Variables are used to store data in scripts. Variables are defined as var_name=value.
  • Conditions: Conditions are used to specify how the script will run under certain conditions. Conditions are created using the keywords if, else and elif.
  • Loops: Loops allow the script to repeatedly execute a command or group of commands. Loops are created using the while, for and until keywords.

Basically, Bash scripting is a powerful tool that can be used repeatedly and automates complex tasks.

The importance of chmod (permissions) in Bash scripts

Bash scripts are an indispensable part of automation in Linux; however, these scripts must have the necessary permissions to run correctly. This is where the 'chmod' command comes in. When you create a Bash script, you may not have permission to run it on this file by default. The 'chmod' command allows you to make this script file executable by giving it execute permission. For example, the command 'chmod +x script_name.sh' adds execute permission to the file named 'script_name.sh'. Permissions are not limited to the ability to run; it is also possible to set read, write and run permissions according to the access of the user, group or others. Therefore, setting the correct chmod permissions is essential if you want to share or execute your script securely. In short, 'chmod' is the key to efficient and secure execution of Bash scripts on Linux.

Understanding #!/bin/bash (shebang line)

When you examine a Bash script, you will usually see a line like '#!/bin/bash' at the very beginning of the file. This special line is called a "shebang" and specifies which interpreter to run the script with.

The #!/bin/bash shebang line is as follows:

#! /bin/bash

Shebang starting with '#!' tells the operating system that this file is a script and should be executed with the interpreter in the specified path. For Bash, this interpreter is specified as '/bin/bash'. However, when scripting for a shell or language other than Bash, the shebang line may change. For example, for Python, a shebang of '#!/usr/bin/python3' is used. The shebang is important when running the script directly from the command line, because this way you do not need to specify which interpreter to run the script with. In short, the shebang line is essential for specifying which shell or programme to execute the Bash script with and ensures that scripts on Linux run correctly.

Introduction to the command line in Linux

Linux is a versatile operating system with a graphical user interface (GUI) as well as a powerful command line interface (CLI). The command line allows users to control the operating system by entering commands directly. Especially for tasks such as system administration, file operations or scripting, the command line is a much faster and more flexible tool than the GUI. Bash is the most widely used command-line shell in Linux.

Users can perform a variety of tasks from the command line, including

  • Managing files and directories
  • Running programmes
  • Changing system settings
  • Perform automation tasks

Basic commands on the command line

There are a wide variety of commands you can use on the command line. Some basic commands are:

  • ls: Lists files and directories.
  • cd: Navigate to a file or directory.
  • mkdir: Creates a new directory.
  • touch: Creates a new file.
  • rm: Deletes a file or directory.
  • cp: Copies a file or directory.
  • mv: Moves a file or directory.
  • cat: Displays the contents of the file.
  • man: Displays a description of the command.

The command line is a starting point for users to automate complex workflows by creating Bash scripts. Learning the command line in Linux gives users deeper control and automation capabilities.

Automating tasks using Bash scripts (cron jobs)

Bash scripts allow users to automate common tasks by combining a series of commands into a single file. Using Bash scripts, users can automate a variety of tasks, including the following:

  • Backup files and directories
  • Analyse logs
  • Update system settings
  • Start and close applications

One way to automate bash scripts is to schedule them with cron. Cron is a task scheduling tool available on Linux operating systems. Using cron, you can run scripts at a specific time or at a specific interval.

To create cron jobs, you can follow the steps below:

  • Open the crontab file using the crontab command.
  • In the crontab file, add the path to the script and the time or interval at which you want to run it.
  • Save the file by pressing Ctrl+O.
  • Close the file by pressing Ctrl+X.

For example, the following crontab line will run the script /home/user/scripts/myscript.sh every day at 09:00:

0 9 * * * /home/kullanıcı/scripts/myscript.sh

Task Scheduling in Linux: Cron and Anacron, you can find more information about cron and anacron.

Using parameters in a Bash script

Bash scripts have the ability to work flexibly with parameters received from the user. This allows the script to be run in different scenarios or with different input values. Parameters are given from the command line when running the script.

To use parameters in the Bash script, you can follow the steps below:

  • In the script, use the - character to define the parameter.
  • In the script, use the format ${parameter_name} to use the parameter.

For example, the following script prompts the user to enter a name and prints it on the screen:

#!/bin/bash

# Define parameter
name=$1

# Use parameter
echo "Hello, ${name}"

To run this script, you can use the following command:

./myscript.sh Makdos

This command will produce the following output:

Hello, Makdos

Using parameters effectively makes scripts more modular and adaptable, so that they can be used for a wide range of applications.

Creating loops in Bash scripts

In Bash scripts, loops are indispensable for repeating a certain command or group of commands until a certain condition is met, or a certain number of times. The most commonly used loops in Bash are 'for' and 'while' loops. The 'for' loop is used to iterate over a specific list. For example, a 'for' loop is ideal for iterating over a list of files or for iterating over a range of numbers. 

For example, the following script lists all files in a directory:

#!/bin/bash

# List all files in the directory
for file in $(ls /home/user/files)
do
  echo $file
done

A 'while' loop is used to repeat commands as long as a certain condition is true.

For example, the following script prompts a user to enter a number until they enter a number less than 10:

#!/bin/bash

# Ask the user to enter a number
number=$1

# Run the loop as long as the number is less than 10
while [ $number -lt 10 ]
do
  echo "Please enter a number less than 10:"
  read number
done

Loops in Bash are one of the keys to creating complex workflows in scripts and maximising automation. Whether it is performing operations on all files in a directory or repeating a series of commands in response to a specific situation, loops in Bash allow you to perform such tasks simply and effectively.

Implementing conditional statements in Bash scripts

In Bash scripts, conditional statements give the ability to execute different commands depending on certain conditions. The most commonly used conditional statements are represented by 'if', 'elif' and 'else'. The combination of these statements allows you to create complex logic structures in your scripts. For example, you can use the 'if [ -e file_name ]; then ... fi' construct to check if a file exists. Conditional statements are also used to compare numeric or textual values. It is also possible to evaluate multiple conditions with the 'case' statement. Using conditional statements effectively in Bash makes scripts more dynamic, flexible and fault tolerant. Determining how a script reacts in response to a given condition reveals the true power of automation in Linux.

The if-else statement is used in the following format:

if condition
then
  # this block is executed if the condition is true
else
  # this block is executed if the condition is false
fi

For example, the following script checks whether a number entered by a user is even:

#!/bin/bash

# Ask the user to enter a number
number=$1

# Check if the number is even
if [ $sayi % 2 -eq 0 ]
then
  echo "The number is even."
else
  echo "The number is odd."
fi

Understanding functions in Bash scripts

Functions in Bash scripts allow you to name and repeatedly call groups of commands that perform a specific function, making your code both more organised and reusable. A function can be defined with the keyword 'function', or you can omit this keyword and use the function name directly. The definition of a function is followed by curly brackets to indicate what the function will do.

For example, the following script defines a function that calculates the square root of a number entered by a user:

#!/bin/bash

# Define the square root function
function karekok()
{
  # Get parameter
  number=$1
  # Calculate square root
  karekok=$(echo "$number" | bc -l sqrt)
  # Rotate square root
  echo $karekok
}
# Call function
karekok 16

This script will produce the following output:

4

Effective use of functions helps make scripts more modular and easy to maintain.

How are variables used in Bash scripts?

Variables are used in Bash scripts to store information and access it later. No special keywords are needed to define a variable; just specify the name of the variable and assign its value with an equals sign (=).

For example, the following script defines a variable to store a number entered by a user:

#!/bin/bash

# Identify the number
number=10

To access the value of this variable, the dollar sign ($) is used, i.e. the echo $number command.

This script will produce the following output:

Number: 10

In Bash, variable names are case-sensitive, so 'variable' and 'variable' are considered two different variables. Also, there are some predefined special variables (e.g. $?, $#, $*, etc.) that store certain information. For example, $? stores the exit status of the last executed command. Using variables effectively allows scripts to become more dynamic, readable and reusable.

Debugging Bash scripts

Errors encountered when writing Bash scripts can be a headache, especially in complex scripts. However, Bash has several useful tools to ease the process of finding and fixing errors in scripts. By running the script with the command bash -x script_name.sh, you can see step-by-step how each line of the script is evaluated and which commands are executed. This is an excellent way to isolate the source of potential problems. You can also use the set -e option in the script to stop the script if an error occurs, and set -u to terminate the script if undefined variables are used. Understanding error messages is critical to correctly diagnosing the problem. Using Bash debugging tools effectively will make your scripts run more reliably and efficiently.

Process control in Bash script

Bash scripts not only execute simple commands in a sequential manner, but also have the ability to control multiple processes or procedures simultaneously.

For process control in Bash scripts, the following techniques can be used:

  • wait command: This command waits for one or more processes to complete.
  • kill command: This command terminates one or more processes.
  • & operator: This operator runs a command in the background.

For example, the '&' operator is used to execute a command in the background. For example, if you use 'command1 & command2', 'command1' runs in the background while 'command2' runs in the foreground. This is particularly useful when you want to run long-running processes in parallel. The 'wait' command is used to wait for a process running in the background to complete. As well as this, the 'trap' command is used to respond to certain signals or events within the script, which is useful for triggering actions such as cleanup tasks in case the script terminates unexpectedly. In general, process control in Bash allows scripts to be more flexible, responsive and performant.

Execution of Bash scripts

After creating a Bash script, it is time to run it. However, the script must have execution permissions before you can run it directly. You can add this permission with the command chmod +x script_name.sh. Once the permissions process is complete, you can run the script as './script_name.sh'. The prefix './' indicates that the script is located in the current directory. 

If you want to run the script in a different directory, you must specify the full path. Alternatively, you can run the script directly with Bash using the command 'bash script_name.sh', in which case execute permission is not required. However, this approach allows the script to be executed with Bash, ignoring the shebang ('#!/bin/bash') line. In general, executing Bash scripts is the key to automation and batch processing of commands in Linux.

Conclusion

Bash scripts are the cornerstone of automation and the efficient execution of repetitive tasks in Linux. In this article, we have covered the basic components of Bash scripting and how to use it effectively. However, the subject of Bash scripting is a very broad field and this is only a beginner's guide. For those who want to learn more advanced Bash scripting techniques, functions, loops and debugging in more depth, there are many online resources and books available.

Also, various online forums and communities are great resources for solving problems and learning new techniques. We wish you success in your Bash scripting journey!

MakdosTech Footer Logo

All Rights Reserved 2024 - Makdos Tech

Sharing of articles without permission or attribution is prohibited.