-1

So I have a task in which I have to create a shell script that takes as arguments a multitude of numbers and their layout and sorts them in ascending or descending order.The problem is that the first argument will be the layout and I have to check if the rest of the arguments (without the first one) will be numbers. For examble

./ex_4.sh dec 4 5 6 0
6
5
4
0

I have tried multiple conditions for if statement but none of them seem to work. If anyone can help me I would be grateful.Thank you!

Here is my code

#!/bin/bash
option=$1 #keeping the first argument
n=${@:2}
#Checking if arguments are numbers
for i in
do
        if [[ "$n" =~ ^[0-9]+$ ]]
        then
                echo "is number"
        else
                echo "not a number"
        fi
done

#Checking if option is incr or dec
case $option in
         incr)
                for i
                do
                      echo $i
                 done | sort -n
                 ;;
          dec)
                 for i
                 do
                      echo $i
                      done | sort -nr
                  ;;
           *)
                  echo "Invalid option";;
esac

When I execute the code with wrong input it prints this:

 ./ex_4.sh incr utdu
utdu
incr
utdu

The correct code should be printing this:

./ex_4.sh incr utdu
not a number
incr
Alexander L. Hayes
  • 3,892
  • 4
  • 13
  • 34
Lian
  • 13
  • 5
  • Always first test your broken script to https://shellcheck.net before asking here. Thanks – Gilles Quénot Dec 15 '22 at 21:28
  • @AlexanderLHayes Please refrain from making cosmetic edits to closed posts, especially when the formatting change doesn't actually affect the rendering at all. – tripleee Dec 16 '22 at 06:28

1 Answers1

0
...
n=${@:2}
#Checking if arguments are numbers
for i in
do
        if [[ "$n" =~ ^[0-9]+$ ]]
...

I take the for i in is a copy&paste mistake, and it is supposed to read for i in $n.

But then, shouldn't it be $i the variable that you test for regexp?

if [[ "$i" =~ ^[0-9]+$ ]]
chrslg
  • 9,023
  • 5
  • 17
  • 31