Shell Script To Reverse Command Line Input / Numbers

in Categories Academic last updated October 20, 2008
#!/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

Share this on:

8 comment

  1. 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

  2. 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 ~]#
    
    1. 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

  3. 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”

    Have a question? Post it on our forum!