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.
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.
Below is the bash script for reversing a number:
Explanation of the script
- `#!/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.
- `echo “Enter a number”`: This line is used to print the message “Enter a number” to the console.
- `read num`: This line reads the user input from the console and stores it in the variable ‘num’.
- `reverse=0`: This line initializes the variable ‘reverse’ to 0. This variable will store the final reversed number.
- `while [ $num -gt 0 ]`: This line starts a while loop which will continue as long as the value in ‘num’ is greater than 0.
- `remainder=$(( $num % 10 ))`: This line calculates the remainder when ‘num’ is divided by 10. This gives the last digit of ‘num’.
- `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.
- `num=$(( $num / 10 ))`: This line updates the value of ‘num’. It divides ‘num’ by 10 to remove the last digit.
- `done`: This keyword ends the while loop.
- `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:
- Save the script in a file. Let’s call it `reverse_num.sh`.
- Open the terminal and navigate to the directory where you saved the script.
- Run the following command to make your script executable:
chmod +x reverse_num.sh
- Now, you can run your script with the following command:
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.
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.