Learn Practical BASH Scripting Projects – Part III

The earlier articles in the ‘Shell Scripting‘ series received great feedback, so I’m writing this article to keep the learning journey going.

Bash Keywords

Bash keywords refer to specific words or commands used in the bash programming language, which is a type of shell that allows users to interact with the operating system by executing textual commands.

Keywords in Bash are special words that have a specific meaning and are recognized by the Bash shell. These keywords are essential for writing scripts and executing various tasks in a Unix-like operating system.

Here are a few examples of Bash keywords:

  • if: Used for conditional statements, where you need to execute certain commands only if a specified condition is true.
  • else: Works in conjunction with the "if" keyword to specify a block of commands to be executed if the condition in the "if" statement is false.
  • fi: It is written backward (as "fi") to show the end of the conditional block.
  • for: Initiates a loop that reruns a block of commands for a mentioned number of times or over a list of items.
  • while: Similar to the "for" keyword, it creates a loop that continues executing a block of commands as long as a specified condition is true.
  • do: Marks the beginning of the block of commands to be executed in a loop (used in conjunction with “for” and “while”).
  • done: Indicates the end of a loop block.
  • case: Used for creating a switch statement, allowing the execution of different commands based on the value of a variable.

These keywords help structure the flow of a Bash script, making it possible to perform complex tasks and automate various processes on a computer. Understanding these keywords is crucial for anyone working with Bash scripts or the command line in Unix-like systems.

Unlike most computer languages, Bash allows keywords to be used as variable names, even though this can make scripts difficult to read. To keep scripts understandable, keywords should not be used for variable names.

A command is implemented in the shell as $(command). You might have to include the full path of the command, for example, $(/bin/date), for correct execution.

You can determine the path of a specific program using the ‘whereis‘ command. For example, to find the path of the date command, you can use the following:

whereis date.

date: /usr/bin/date /usr/share/man/man1/date.1.gz /usr/share/man/man1/date.1fun.gz

Change Directory Levels with Script

The following script is used to move from the current working directory to any higher level by simply providing a numerical value at the end of the script during execution.

#!/bin/bash

LEVEL=$1

# Initialize CDIR to the current directory
CDIR="."

# Loop to move up the directory levels
for ((i = 1; i <= LEVEL; i++)); do
    CDIR="../$CDIR"
done

# Change to the calculated directory
cd "$CDIR" || exit

# Print the current working directory
echo "You are in: $PWD"

# Start a new Bash session
exec /bin/bash

To use the script, provide the desired level as a command-line argument when executing it as shown.

./change_directory.sh 2

Replace 2 with the actual number of directory levels you want to move up. This script can be useful for navigating through directory structures in the terminal efficiently.

Create a Random File or Folder

The following script is used to print the current username, system uptime information along with the current date and time, and appends this data to a text file.

Finally, the script shows the user of the directory where the file is being saved using the pwd command, which prints the current working directory.

#! /bin/bash

echo "Hello $USER"
echo "$(uptime)" >> "$(date)".txt
echo "Your File is being saved to $(pwd)"

We understand that the output of the `date` command includes the current date, time in hours, minutes, seconds, and the year. This information allows us to create an organized file name without the risk of filename duplication. This capability is particularly useful when a user requires a file to be generated with a timestamp for future reference.

Shell Script to Collect Network Information

This collectnetworkinfo.sh script gathers detailed network configuration information from a Linux system and compiles it into a text file for analysis or troubleshooting purposes.

Note: You might need to install the `lsb-core` package and other required packages and dependencies. Use the `apt` or `yum` package manager to install the necessary packages.

It is essential to have root privileges to execute the script since many of the commands used in the script are configured to be run with root permissions.

The final output file, named with a timestamp, serves as a comprehensive report on the network configuration of the Linux system. The script encourages the user to email this file to a specified support email address for further assistance or analysis.

Shell Script to Converts UPPERCASE to Lowercase

A script that converts UPPERCASE to lowercase and redirects the output to a text file “small.txt” which can be modified as required.

#!/bin/bash 

echo -n "Enter File Name : " 
read fileName 

if [ ! -f $fileName ]; then 
  echo "Filename $fileName does not exists" 
  exit 1 
fi 

tr '[A-Z]' '[a-z]' < $fileName >> small.txt

This above script can convert the case of a file of any length with a single click from uppercase to lowercase and vice-versa if required, with little modification.

Create a Simple Calculator in Bash

The following bash script is a simple calculator program that allows the user to perform basic arithmetic operations such as addition, subtraction, multiplication, and division.

#! /bin/bash 
clear 
sum=0 
i="y" 

echo " Enter one no." 
read n1 
echo "Enter second no." 
read n2 
while [ $i = "y" ] 
do 
echo "1.Addition" 
echo "2.Subtraction" 
echo "3.Multiplication" 
echo "4.Division" 
echo "Enter your choice" 
read ch 
case $ch in 
    1)sum=`expr $n1 + $n2` 
     echo "Sum ="$sum;; 
        2)sum=`expr $n1 - $n2` 
     echo "Sub = "$sum;; 
    3)sum=`expr $n1 \* $n2` 
     echo "Mul = "$sum;; 
    4)sum=`expr $n1 / $n2` 
     echo "Div = "$sum;; 
    *)echo "Invalid choice";; 
esac 
echo "Do u want to continue (y/n)) ?" 
read i 
if [ $i != "y" ] 
then 
    exit 
fi 
done

Did you see how easy it was to create a powerful program for calculations in such a straightforward manner? This isn’t the end. We will be presenting at least one more article in this series, covering a broad perspective from an administrative viewpoint.

Hey TecMint readers,

Exciting news! Every month, our top blog commenters will have the chance to win fantastic rewards, like free Linux eBooks such as RHCE, RHCSA, LFCS, Learn Linux, and Awk, each worth $20!

Learn more about the contest and stand a chance to win by sharing your thoughts below!

Ravi Saive
I am an experienced GNU/Linux expert and a full-stack software developer with over a decade in the field of Linux and Open Source technologies

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

7 Comments

Leave a Reply
  1. #!/bin/bash
    while :
    do
    ops==+-*/
    opwords=( ” Sum Difference Product Quotient )
    sum=0
    read -ep “Enter first no.: ” n1
    read -ep “Enter second no.: ” n2
    printf “%d. %s\n” 1 Addition 2 Subtraction 3 Multiplication 4 Division
    read -sn1 -ep “Enter your choice: ” ch
    (( ch > 0 && ch < 5 )) &&
    printf '%s: %d\n' "${opwords[ch]}" "$(( n1 ${ops:ch:1} n2 ))" ||
    echo "Invalid choice"
    read -sn1 -ep "Do you want to continue (y/n)?" i
    [[ $i != "y" ]] && exit
    done

    Reply
  2. in up.sh script, why it is needed to have exec /bin/bash at the end. I tried without last line and it does not work.

    Thanks in advance

    Reply
  3. Hi Team ,

    Can you please explain how the rcmd command is working & how can i run multiple commands on remote machine by using the rcmd command. It will be useful if get the reply with the new post .

    Regards,
    Saravanan

    Reply
  4. #!/bin/bash
    while :
    do
    ops==+-*/
    opwords=( ” Sum Difference Product Quotient )
    sum=0
    read -ep “Enter first no.: ” n1
    read -ep “Enter second no.: ” n2
    printf “%d. %s\n” 1 Addition 2 Subtraction 3 Multiplication 4 Division
    read -sn1 -ep “Enter your choice: ” ch
    (( ch > 0 && ch < 5 )) &&
    printf '%s: %d\n' "${opwords[ch]}" "$(( n1 ${ops:ch:1} n2 ))" ||
    echo "Invalid choice"
    read -sn1 -ep "Do you want to continue (y/n)?" i
    [[ $i != "y" ]] && exit
    done

    Reply
  5. How can an article using expr for arithmetic (especially with #!/bin/bash as the shebang) be taken seriously?

    if [ $i != “y” ] is unnecessary.

    Reply
    • Hi Chris,

      Could you elaborate? How would you change it? The test is inherent to the while statement and thus not needed. Correct?

      rc

      Reply
  6. just a small correction of the script

    #! /bin/bash
    clear
    i=”y”
    while [ $i = “y” ]
    do
    sum=0

    echo ” Enter one no.”
    read n1
    echo “Enter second no.”
    read n2

    echo “1.Addition”
    echo “2.Subtraction”
    echo “3.Multiplication”
    echo “4.Division”
    echo “Enter your choice”
    read ch
    case $ch in
    1)sum=`expr $n1 + $n2`
    echo “Sum =”$sum;;
    2)sum=`expr $n1 – $n2`
    echo “Sub = “$sum;;
    3)sum=`expr $n1 \* $n2`
    echo “Mul = “$sum;;
    4)sum=`expr $n1 / $n2`
    echo “Div = “$sum;;
    *)echo “Invalid choice”;;
    esac
    echo “Do u want to continue (y/n)) ?”
    read i
    if [ $i != “y” ]
    then
    exit
    fi
    done

    Reply

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.