🚀 Think you’ve got what it takes for a career in Data? Find out in just one minute!

What is Bash scripting?

-
4
 m de lecture
-

Scripting offers users the ability to simplify and streamline their daily operations. Bash scripts (short for Bourne Again Shell) are very powerful and useful components for development.

It is a command-line interpreter for Unix and Linux systems. Designed by Brian Fox in 1989 for the GNU project, it was developed to replace the original Bourne Shell, bringing significant improvements in terms of functionality and compatibility.

The importance of Bash in system administration and software development cannot be underestimated. It allows for the automation of repetitive tasks, management of large-scale systems, and the facilitation of complex script development for various applications.

The Basics of Bash Scripting

Bash scripting is an essential skill for anyone working with Unix or Linux systems.

Bash and Bang: Introduction to the Shebang

The first key element of any Bash script is the shebang line. It tells the system which interpreter to use to execute the script.

				
					#!/bin/bash
				
			

The #! is known as a shebang, and /bin/bash specifies the path to the Bash interpreter. This line is crucial because it ensures that the script will be interpreted by Bash, even if other shells are present on the system.

First Step: Hello World!

With your favorite text editor, create a file called hello.sh, and add the following content, then save it:

				
					#!/bin/bash
echo "Hello World!"
				
			

Making a Script Executable

By default, a text file does not have the necessary permissions to be executed like a program. To make your script executable, you need to use the following command to change the permissions:

				
					chmod +x hello.sh
				
			

You can then check the permissions with the following command:

				
					ls -l hello.sh
				
			

Running a Script

To run the script, we have several options:

  • Relative Path:
				
					./hello.sh
				
			
  • Using the Bash shell:
				
					bash hello.sh
				
			
  • Via the sh shell, but this may cause different behaviors if the script uses specific Bash features:
				
					sh hello.sh
				
			

Basic Commands

Bash scripting relies on the effective use of a variety of commands to perform simple and complex tasks. Here are some commonly used commands for navigating and manipulating the filesystem:

  • List files and folders in the current directory
				
					ls
				
			
  • Change directory
				
					cd /path/to/directory
				
			
  • Display the current directory
				
					pwd
				
			
  • Create an empty file or update the timestamp of an existing file
				
					touch newfile.txt
				
			
  • Delete files or folders
				
					rm file.txt
				
			

Combining Commands

Bash scripts become powerful when you combine commands to perform more complex tasks. Here are some examples:

  • Use the ;” to execute multiple commands in a sequence
				
					cd /path/to/directory; ls; pwd
				
			
  • Redirect output: Use > to redirect the output of a command to a file, or >> to append to an existing file
				
					echo "Hello, World!" > hello.txt
echo "Hello again!" >> hello.txt
				
			
  • Use the Pipe ( | ) to send the output of one command as input to another command
				
					ls -l | grep ".txt"
				
			

Variables and Substitution

  • Declare a variable and use it with $
				
					NAME=”Alice”
echo “Hello, $NAME!”
				
			
  • Use substitution to take the output of a command and use it as a variable
				
					DATE=$(date)
echo "Today's date is $DATE"
				
			

Note that this example is often used in log creation

Managing Paths

Understanding and managing file paths is essential for efficiently navigating the filesystem and writing robust scripts.

Absolute Path vs Relative Path

Image Absolute Image Relative
Specifies the complete location of a file or directory from the root of the filesystem. Indicates the location of a file or directory relative to the current directory.
Example : /home/user/documents/report.txt Example : documents/report.txt

Associated Commands

To locate files and commands, several tools are available in Bash:

  • Find the location of an executable
				
					which bash
				
			
  • Location of binaries, sources, and documentation associated with a command
				
					whereis bash
				
			
  • Search for files and folders
				
					find /home/user -name "report.txt"
				
			

Environment Variables

Environment variables are key-value pairs that affect the behavior of system processes. Here are the most common ones:

  • $PATH: Contains a list of directories where the system looks for executables. To modify it, use the following command
				
					export PATH=$PATH:/new/directory/path
				
			
  • $HOME: Represents the user’s home directory
				
					echo $HOME
cd $HOME
				
			
  • $PWD: Indicates the current working directory
				
					echo $PWD
				
			
  • $USER: Contains the name of the current user
				
					echo $USER
				
			

Flow Control and Logic

Flow control and logic are essential elements of Bash scripting, allowing for the creation of dynamic and adaptable scripts.

Conditional Statements

They allow for code execution based on certain conditions. Here is an example illustrating the use of if…elif…else.

				
					#!/bin/bash
echo "Enter a number: "
read number
if [ $number -gt 10 ]; then
    echo "The number is greater than 10."
elif [ $number -eq 10 ]; then
    echo "The number is equal to 10."
else
    echo "The number is less than 10."
fi
				
			

Loops

Loops are used to repeat commands multiple times.

  • for
				
					for i in 1 2 3 4 5; do
    echo "Counter : $i"
done
				
			
  • while
				
					count=1
while [ $count -le 5 ]; do
    echo "Counter: $count"
    ((count++))
done

				
			
  • until
				
					count=1
until [ $count -gt 5 ]; do
    echo "Counter : $count"
    ((count++))
done
				
			

Some Useful Scripts and Best Practices

Sample Scripts

  • Backup Script: Copies files from a source to a destination
				
					#!/bin/bash
# This script performs a backup of files
src="/home/user/documents"
dest="/backup/documents"

if [ ! -d $dest ]; then
    mkdir -p $dest
fi

for file in $src/*; do
    if [ -f $file ]; then
        cp $file $dest
        echo "Copié $file vers $dest"
    fi
done
				
			
  • Cleanup: Deletes items from a temporary folder
				
					#!/bin/bash
dir="/home/user/temp"
echo "Cleaning up the directory $dir"

for file in $dir/*; do
    if [ -f $file ]; then
        rm $file
        echo "Deleted $file"
    fi
done
				
			

Some Best Practices

1. Comment: This makes scripts more readable and understandable

2. Name your variables descriptively. Avoid variable names like $var1, $var2, or $tmpvar.

3. Handle errors: Use conditions to check for success and capture errors appropriately

4. Modularize your code using functions, especially if the script performs multiple operations, for example:

				
					backup_files() {
    # Code to perform the backup
}
				
			

5. Debug to identify errors. Here are useful commands for this:

				
					#!/bin/bash
set -x # Enables trace mode, displaying each command and its result
# Script code

#!/bin/bash
set -e # Stops the script on errors
# Script code

echo "Starting the script" # Use echo at strategic points in the script to check outputs and follow the execution flow
				
			

To Conclude

Bash scripting is a powerful tool to automate and simplify tasks on Unix and Linux systems. By mastering the basics, basic commands, path management, flow control, and best practices, you can write robust and effective scripts to improve your daily productivity.

Facebook
Twitter
LinkedIn

DataScientest News

Sign up for our Newsletter to receive our guides, tutorials, events, and the latest news directly in your inbox.

You are not available?

Leave us your e-mail, so that we can send you your new articles when they are published!
icon newsletter

DataNews

Get monthly insider insights from experts directly in your mailbox