Palindromic numbers are numbers that remain the same when their digits are reversed. For example, the number “121” is a palindrome because it reads the same backward as forward. In this article, we will write a simple Bash script to check if a number is a palindrome.
Before we begin, ensure that you have a Linux or Unix-like operating system with a Bash shell. Bash (Bourne Again Shell) is a popular command-line interface for Unix-based systems.
Understanding the Concept
To determine if a number is a palindrome, we need to reverse the number and compare it to the original. If the reversed number is the same as the original, then it’s a palindrome; otherwise, it’s not.
Writing the Bash Script
Here is a simple script that accepts a number from the user, reverses it, and then checks if it’s a palindrome:
To run the script, save it to a file such as palindrome_check.sh, make the file executable using `chmod +x palindrome_check.sh`, and run the script using ./palindrome_check.sh.
Breaking Down the Script
Now let’s break down this script to understand how it works:
- Line 1 #!/bin/bash: This is a shebang (#!). It informs the system that this script should be executed with bash shell.
- Lines 3-4: This is where the script asks for input from the user. The -n option in echo -n prevents a newline, and read num reads the user’s input into the variable num.
- Line 7: The original number is stored in original_num to be used for comparison later.
- Lines 10-17: These lines contain a while loop to reverse the number. Here’s the breakdown:
- The while [ $num -gt 0 ] condition keeps the loop running as long as num is greater than 0.
- In the loop, the modulus operator (%) is used to get the last digit of the number, which is stored in remainder.
- The rev variable is multiplied by 10 and then added to remainder to construct the reversed number.
- Finally, the number is divided by 10 (integer division), effectively removing the last digit. This continues until all digits have been reversed.
- Lines 20-26: These lines check if the reversed number (rev) equals the original number (original_num). If they are the same, it means the number is a palindrome, and a corresponding message is displayed.
This bash script provides a simple yet practical way to check for palindromic numbers. While there might be more advanced or optimized ways to perform this operation, this script gives a good start to those learning shell scripting in Linux. As with any code, make sure to understand each part thoroughly before incorporating it into your projects.