Prahlad Inala
Prahlad Inala

Follow

Prahlad Inala

Follow
Bash Scripting Basics

Bash Scripting Basics

Prahlad Inala's photo
Prahlad Inala
ยทApr 6, 2022ยท

6 min read

Play this article

Table of contents

What is Bash Scripting

Bash Scripting is a list of commands in a computer program that is run by the Linux shell which is a command-line interpreter.

Bash scripting is a method of automating tasks in the Unix shell. It allows users to write scripts in the Bash language, which are interpreted by the shell, to automate complex and repetitive tasks.

Here are some basic elements of bash scripting:

  1. Shebang line: The first line of a bash script should start with "#!/bin/bash". This line is called the shebang line and is used to specify the interpreter for the script.

  2. Variables: Variables in bash scripting are declared with a name, an equal sign (=), and a value. For example: name="John".

  3. Command line arguments: Bash scripts can accept command line arguments, which are passed to the script when it is executed. The arguments can be accessed in the script using the special variables $1, $2, etc.

  4. Conditional statements: Bash scripts can use conditional statements like if and case to make decisions based on the values of variables or the results of commands.

  5. Loops: Bash scripts can use loops like for and while to repeat commands multiple times.

  6. Functions: Functions allow you to group commands together under a single name, making it easier to reuse code.

  7. Input/Output redirection: Bash scripts can redirect input and output to and from files, as well as other commands.

These are just a few of the basic elements of bash scripting. With these tools, you can write complex and powerful scripts to automate tasks and make your life easier.

It is recommended to start with simple scripts and gradually build your knowledge and experience with bash scripting. The manual pages (man bash) and online resources can be a great help for learning more about bash scripting.

History of Bash

Bash (Bourne-Again SHell) is a Unix shell and command language that was developed as a free software replacement for the original Unix shell, the Bourne shell (sh). Bash was first released in 1989 and has since become one of the most widely used shells for Unix-based systems.

Bash was developed by Brian Fox for the GNU Project as part of the effort to develop a free software operating system. The goal of the project was to provide a shell that was compatible with the Bourne shell but with added features and improved functionality. Bash was designed to be a more flexible and powerful shell than the original Bourne shell and quickly gained popularity among Unix users.

Over the years, Bash has been continually updated and improved, with new features and functionality added with each release. It has become a staple tool for system administrators, developers, and power users, providing a powerful and flexible environment for automating tasks, managing systems, and performing complex operations.

Today, Bash is included in many Unix-based systems, including Linux, macOS, and other popular operating systems, and is widely used in a variety of applications, from system administration and scripting to software development and automation. Its popularity and versatility have made it an important component of the Unix toolset and a critical component of the open source software ecosystem.

Advantages of Using Bash/Shell Scripting

  1. Reusability

  2. Automating Boring tasks

  3. SysAdmins Can create a script to take regular backups

  4. Easy debugging

  5. Can avoid mistakes that are done in manual configuration

Basic Bash Scripting

Variables

# Declaring and Initializing a Variable
NAME="Prahlad"
# Calling a Variable
echo $NAME
echo "$NAME"
echo "${NAME}!"

# Output:
# Prahlad

String

NAME="Prahlad"

Shell Execution

echo "Hello my current directory is $(pwd)"
echo "Hello my current directory is `pwd` "

Conditional Execution

Functions

my_name(){
    echo "Prahlad"
}

echo "My name is $(my_name)"

Conditionals

if [[ -z "$string" ]];
then
 echo "String is empty"
elif [[ -n "$string"]]; 
then
 echo "String is not empty"
fi

Loops in Bash Scripting

In bash scripting, loops are used to repeat a set of commands for a specified number of times or until a certain condition is met. There are several types of loops in bash, including for loops and while loops.

For Loop

A for loop is used to execute a set of commands for a specified number of times.

#!/bin/bash
for i in {1..10}; do
  echo $i
done

While Loop

A while loop is used to execute a set of commands while a certain condition is true.

#!/bin/bash
i=1
while [ $i -le 10 ]; do
  echo $i
  i=$((i + 1))
done

Example Codes for Bash Scripting

Example 1: Printing "Hello, World!"

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

Example 2: Accepting command line arguments and printing them

#!/bin/bash
echo "First argument: $1"
echo "Second argument: $2"
echo "Third argument: $3"

Example 3: Conditional statement (checking if a number is positive or negative)

#!/bin/bash
read -p "Enter a number: " num
if [ $num -lt 0 ]; then
  echo "$num is negative."
else
  echo "$num is positive."
fi

Example 4: Loop (printing numbers 1 to 10)

#!/bin/bash
for i in {1..10}; do
  echo $i
done

Example 5: Function (calculating the factorial of a number)

#!/bin/bash
factorial() {
  local num=$1
  local result=1
  for ((i=1; i<=num; i++)); do
    result=$((result * i))
  done
  echo $result
}

read -p "Enter a number: " num
factorial $num

Example 6: Copying files

#!/bin/bash
read -p "Enter the source file path: " source_file
read -p "Enter the destination file path: " destination_file
cp $source_file $destination_file

Example 7: Listing the contents of a directory

#!/bin/bash
read -p "Enter the directory path: " directory
ls $directory

Example 8: Renaming files in bulk

#!/bin/bash
read -p "Enter the source file extension: " source_extension
read -p "Enter the destination file extension: " destination_extension
for file in *.$source_extension; do
  mv "$file" "${file%.$source_extension}.$destination_extension"
done

Example 9: Printing the top 10 largest files in a directory

#!/bin/bash
read -p "Enter the directory path: " directory
cd $directory
ls -S | head -n 10

Example 10: Checking if a website is up

#!/bin/bash
read -p "Enter the website URL: " url
status_code=$(curl -s -o /dev/null -w "%{http_code}" $url)
if [ $status_code -eq 200 ]; then
  echo "$url is up."
else
  echo "$url is down."
fi

Example 11: Compressing files

#!/bin/bash
read -p "Enter the source file path: " source_file
tar -zcvf "${source_file}.tar.gz" $source_file

Example 12: Deleting files older than a certain number of days

#!/bin/bash
read -p "Enter the directory path: " directory
read -p "Enter the number of days: " days
find $directory -type f -mtime +$days -delete

Example 13: Counting the number of lines in a file

#!/bin/bash
read -p "Enter the file path: " file
wc -l $file

Example 14: Searching for a string in a file

#!/bin/bash
read -p "Enter the file path: " file
read -p "Enter the search string: " search_string
grep $search_string $file

Example 15: Running multiple commands in parallel

#!/bin/bash
command1 &
command2 &
command3 &
wait

Example 7: Listing the contents of a directory

Did you find this article valuable?

Support Prahlad Inala by becoming a sponsor. Any amount is appreciated!

See recent sponsors |ย Learn more about Hashnode Sponsors
ย 
Share this