Shell script to read a number and find whether the number is odd or even

by on April 5, 2008 · 8 comments

  1. #!/bin/bash
  2. # Shell script to read a number and find whether the number is odd or even
  3. # -------------------------------------------------------------------------
  4. # Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
  5. # This script is licensed under GNU GPL version 2.0 or above
  6. # -------------------------------------------------------------------------
  7. # This script is part of nixCraft shell script collection (NSSC)
  8. # Visit http://bash.cyberciti.biz/ for more information.
  9. # -------------------------------------------------------------------------
  10.  
  11. echo -n "Enter numnber : "
  12. read n
  13.  
  14. rem=$(( $n % 2 ))
  15.  
  16. if [ $rem -eq 0 ]
  17. then
  18. echo "$n is even number"
  19. else
  20. echo "$n is odd number"
  21. fi


4000+ howtos and counting! If you enjoyed this article, join 45000+ others and get free email updates!

Click here to subscribe via email.

  • Aakash Alfred

    # On the third line: Instead of rem=$(( $n % 2 ))
    # You can use ;
    rem= `expr $n % 2`

  • Kristada673

    @Aakash Alfred: No buddy, that doesn’t work. It displays everything as odd……..

  • bhaskar

    correct it as:
    if [ $rem -eq ‘0’ ]

  • novendra

    $(( $n % 2 ))
    this syntax not work properly in shell script
    error in brackets

  • Jon disnard

    is_even() {
    case $(( 10#$1 % 2 )) in
    0) return 0 ;;
    *) return 1 ;;
    esac
    }

  • Myd

    odd() { let ${1: -1}%2 && return 0; return 1; }

  • nibash

    if[ $($n % 2) -eq 0]
    then
    echo “even”
    else
    echo “odd”

  • Saikiran

    echo “Program to check even or odd number”
    echo “Enter a number”
    read n
    a=`expr $n % 2`
    if [ $a -eq 0 ] ; then #Semicolon is most important for Executing if-else
    echo “It is an even number”
    else
    echo “It is an odd number”
    fi

Previous Script:

Next Script: