In this tutorial, you will see how to convert numbers to words using bash script. This shell script can be done with the help of switch case statement and while loop.
Sample Input: 54
Sample Output: Five Four
1. SOURCE CODE
(numwords.sh)
# shell function
disp()
{
case $1 in
0)
ss="Zero "$ss
;;
1)
ss="One "$ss
;;
2)
ss="Two "$ss
;;
3)
ss="Three "$ss
;;
4)
ss="Four "$ss
;;
5)
ss="Five "$ss
;;
6)
ss="Six "$ss
;;
7)
ss="Seven "$ss
;;
8)
ss="Eight "$ss
;;
9)
ss="Nine "$ss
;;
esac
}
# infinite loop
while :
ss=""
do
# display server name
echo "Server Name: $(hostname)"
echo "--------------------------------------"
echo "\t\tNumbers to Words Conversion"
echo "--------------------------------------"
echo "Enter a Number: "
read n
# check when number comes to 0
while [ $n -ne 0 ]
do
# r=`expr $n % 10`
# r=$(($n%10))
r=`expr $n % 10`
disp $r
n=`expr $n / 10`
done
echo "$ss"
echo "Do you want to continue? Press Yes or No: "
read ch
if [ $ch = "yes" ] || [ $ch = "Yes" ] || [ $ch = "YES" ]
then
continue
else
exit
fi
done
NOTE
- The space should be given before and after for the equal operator, while comparing the strings otherwise it will return false.
2. OUTPUT
Related Tutorials
1. Arrays in Bash Script
2. Strings in Bash Script
3. Cat Commands in Linux
4. aafire command in linux