Shell script to read a number and write the number in words

Script logic is as follows:

a) First read number into a shell variable

b) Next get one digit at a time

c) Use simple case control structure and loop to find digit equivalent in words

Sample script to convert numbers into equivalent words

#!/bin/bash
# Shell script to read a number and write the number in words. Use case
# control structure. For example 12 should be print as one two
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
echo -n "Enter number : "
read n
 
len=$(echo $n | wc -c)
len=$(( $len - 1 ))
 
echo "Your number $n in words : "
for (( i=1; i<=$len; i++ ))
do
   # get one digit at a time
    digit=$(echo $n | cut -c $i)
   # use case control structure to find digit equivalent in words 
    case $digit in
        0) echo -n "zero " ;;
        1) echo -n "one " ;;
        2) echo -n "two " ;;
        3) echo -n "three " ;;
        4) echo -n "four " ;;
        5) echo -n "five " ;;
        6) echo -n "six " ;;
        7) echo -n "seven " ;;
        8) echo -n "eight " ;;
        9) echo -n "nine " ;;
    esac	
done
 
# just print new line
echo ""
Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
CategoryList of Unix and Linux commands
File Management cat
Firewall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN CentOS 8 Debian 10 Firewall Ubuntu 20.04
5 comments… add one
  • Chetan Khatri Sep 6, 2016 @ 18:33

    Shell Script to convert number-to-words in US format. Refer below URL

    https://github.com/ckkhatri/LinuxScript/blob/master/number2words.sh

  • free_one Jun 4, 2013 @ 7:46

    Really hepful but I have an error: Bad for loop variable. What can I do to fix this?

  • praveen Aug 13, 2010 @ 7:02

    write a shell script program to check the file is readable or writable using nested if else then fi

  • satyen Aug 27, 2009 @ 11:23

    very helpful for new users

  • DIVYA Aug 25, 2009 @ 13:09

    shell script to convert a given number input into a word

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.