Home > OS >  How to test if arguments are numbers in bash
How to test if arguments are numbers in bash

Time:12-16

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

CodePudding user response:

...
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] $ ]]

CodePudding user response:

Instead of verifying the numbers one by one you could test them all at once:

[[ "${*:2}" =~ ^[^0-9] ( [0-9] )*$ ]] || exit 1

And for the ascending or descending order, you could store the sort command it in an array and add the -r depending on the value of the first argument:

sort_command=( sort -n )

case $1 in
    incr) ;;
    decr) sort_command =( -r ) ;;
    *) exit 1 ;;
esac

printf '%s\n' ""${@:2}" |
"${sort_command[@]}"
  • Related