Wednesday, January 16, 2013

Numpalindrome

This is a nice little bash script that takes a user-inputted number and checks to see if it is a palindrome. I like the logic, which is very simple but elegant. This isn't a practical script, but it was a useful exercise.


#!/bin/bash

#determines if an input number is a palindrome

read -p "please enter a number: " num
orignum=$num

while [ $num -gt 0 ]
do
  digit=$(( num%10 ))
num=$(( num/10 ))
rev=$(( digit + rev*10 ))
done

echo "your number: $orignum"
echo "the reversed number: $rev"
[[ $rev == $orignum ]] && echo "your number is a palindrome." || echo "your number is not a palindrome."

No comments:

Post a Comment