A bash script is a plain text file that contains a series of commands. These commands are a sequence of orders for a UNIX-based operating system to run. This script can be executed in two ways: by executing the script file as an input to the bash command, or by specifying the script file as an executable file.

Advertisement

In this article, we’ll illustrate how to create a bash script that reverses a given number. For example, if the input is `12345`, the script will output `54321`. Let’s dive in.

Bash Script

Below is the bash script for reversing a number:

Explanation of the script

  1. `#!/bin/bash`: This line is known as a shebang. It is used to tell the system that this script needs to be executed using bash shell.
  2. `echo “Enter a number”`: This line is used to print the message “Enter a number” to the console.
  3. `read num`: This line reads the user input from the console and stores it in the variable ‘num’.
  4. `reverse=0`: This line initializes the variable ‘reverse’ to 0. This variable will store the final reversed number.
  5. `while [ $num -gt 0 ]`: This line starts a while loop which will continue as long as the value in ‘num’ is greater than 0.
  6. `remainder=$(( $num % 10 ))`: This line calculates the remainder when ‘num’ is divided by 10. This gives the last digit of ‘num’.
  7. `reverse=$(( $reverse * 10 + $remainder ))`: This line calculates the new reverse number. It multiplies the current ‘reverse’ value by 10 and adds the ‘remainder’ to it.
  8. `num=$(( $num / 10 ))`: This line updates the value of ‘num’. It divides ‘num’ by 10 to remove the last digit.
  9. `done`: This keyword ends the while loop.
  10. `echo “Reversed number is : $reverse”`: This line prints the reversed number to the console.

Running the Script

To run this script, follow the steps below:

  1. Save the script in a file. Let’s call it `reverse_num.sh`.
  2. Open the terminal and navigate to the directory where you saved the script.
  3. Run the following command to make your script executable:
    chmod +x reverse_num.sh 
    
  4. Now, you can run your script with the following command:
    ./reverse_num.sh 
    

You should see a prompt asking you to enter a number. After inputting a number and hitting enter, you’ll see the reverse of the number you provided.

Conclusion

Writing a bash script to reverse a number is an excellent way to familiarize yourself with bash scripting basics. With bash scripts, you can automate tasks, perform calculations, and much more. Mastering this skill will make you a more efficient and effective programmer.

Share.
Leave A Reply


Exit mobile version