≡ Menu

Shell Script To Reverse Command Line Input / Numbers

#!/bin/bash
# Write a shell program that outputs all integers upto the command line
# parameter starting from 1 and also should output the same numbers
# in the reverse order.
# --------------------------------------------------------------------
# This is a free shell script under GNU GPL version 2.0 or above
# Copyright (C) 2005 nixCraft project.
# Feedback/comment/suggestions : http://cyberciti.biz/fb/
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
if [ $# -eq 0 ]
then
	echo "$0 num1, num2, numN"
	exit 1
fi
x=""
echo -n "Numbers are : "
for n in $@
do
  echo -n $n
  echo -n " "
  x="$n $x"
done
echo ""
echo -n "Reverse order: "
echo $x

Comments on this entry are closed.

  • Quetzal

    if [ $# -lt 1 ]; then echo “Usage: $(basename $0) arg1 arg2 … argN “; exit 1; fi

    echo “Numbers are: $@”
    for n in $@; do x=”$n $x”; done
    echo “Reverse order: $x”

  • I am getting wrong results.. Is there anything wrong???

    [root@www ~]# sh reverse.sh 3,4,9,12
    Numbers are : 3,4,9,12
    Reverse order: 3,4,9,12
    [root@www ~]# cat reverse.sh
    #!/bin/bash
    # Write a shell program that outputs all integers upto the command line
    # parameter starting from 1 and also should output the same numbers
    # in the reverse order.
    # --------------------------------------------------------------------
    # This is a free shell script under GNU GPL version 2.0 or above
    # Copyright (C) 2005 nixCraft project.
    # Feedback/comment/suggestions : http://cyberciti.biz/fb/
    # -------------------------------------------------------------------------
    # This script is part of nixCraft shell script collection (NSSC)
    # Visit http://bash.cyberciti.biz/ for more information.
    # -------------------------------------------------------------------------
    if [ $# -eq 0 ]
    then
            echo "$0 num1, num2, numN"
            exit 1
    fi
    x=""
    echo -n "Numbers are : "
    for n in $@
    do
      echo -n $n
      echo -n " "
      x="$n $x"
    done
    echo ""
    echo -n "Reverse order: "
    echo $x
    [root@www ~]#
    
  • Arun

    Hey, CLA`s cannot be passed to the script using commas,
    sh reverse.sh 3 4 9 12

    Use space instead of comma. :)

    Cheers,
    Arun D Patil

  • Thanks a lot for the article.Thanks Again. Fantastic.

  • it is so usefull for students……

  • Aryan

    Thanks This is easiest and shortest way

  • Annonymous

    Is there a way to get the result to print out on separate lines? e.g.

    Numbers are: 1 2 3 4
    Reverse Order:
    1
    2
    3
    4