In this article, we will discuss how to write a shell script to check whether a given number is a palindrome or not.
What is Palindrome number?
A palindrome is a number that remains the same when its digits are reversed. For example, 121 is a palindrome, but 123 is not.
Let’s dive into the code!
Before we get started, let’s briefly discuss what shell scripting is. A shell script is a computer program designed to be run by the Unix/Linux shell, which is a command-line interpreter. Shell scripts are used to automate tasks, manipulate files, and perform other operations in a Unix/Linux environment.
Now, let’s take a look at the shell script to check whether a given number is a palindrome or not.
Shell Script to check whether a given number is a palindrome or not
echo "Enter a number: "
while [ $number -ne 0 ]
remainder=$(( $number % 10 ))
reverse=$(( $reverse * 10 + $remainder ))
number=$(( $number / 10 ))
if [ $original -eq $reverse ]
echo "$original is a palindrome."
echo "$original is not a palindrome."
Let’s go through this script step by step:
- The first line
#!/bin/bashis called a shebang line. It tells the system that this file is a shell script and should be interpreted using the Bash shell.
echocommand is used to prompt the user to enter a number.
readcommand is used to read in the number entered by the user and store it in the variable
whileloop is used to reverse the number. We store the original number in the variable
original, and we use the variables
remainderto reverse the digits of the number.
- In each iteration of the loop, we use the modulo operator
%to get the remainder when the number is divided by 10. We then add this remainder to the reverse variable multiplied by 10, which shifts the digits of the reverse variable one place to the left. We divide the number by 10 to remove the last digit.
- After the loop has completed, we check whether the original number is equal to the reverse number. If they are equal, we print out a message saying that the number is a palindrome. Otherwise, we print out a message saying that the number is not a palindrome.
Now that we understand how this script works, let’s see how we can run it. To run this script, save it in a file with a
.sh extension (e.g.
palindrome.sh), make the file executable with
chmod +x palindrome.sh, and then run the script with
In conclusion, this shell script can be used to check whether a given number is a palindrome or not. It is a simple yet useful tool that can be used to test a variety of numbers. With a little bit of knowledge of shell scripting, anyone can create scripts like this to automate tasks and simplify their workflow.