≡ Menu

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

#!/bin/bash
# Shell script to read a number and find whether the number is odd or even
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project 
# 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 numnber : "
read n
rem=$(( $n % 2 ))
if [ $rem -eq 0 ]
then
  echo "$n is even number"
else
  echo "$n is odd number"
fi

Comments on this entry are closed.

  • 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

  • Sammy Le Jerk

    nevermind

  • Sammy Le Jerk

    read n
    n2=`expr $n % 2`
    if [ $n2 -eq 0 ];
    then
    echo “even”
    else
    echo “odd”
    fi