0

i want a shell script which takes as arguments a set of numbers and the array and sorts them in ascending or descending order.Also i should make the appropriate checks to ensure that the arguments given will be numbers (after 1st argument). output:

./script1.sh incr 4 5 6 0
0
4
5
6

./script2.sh dec 4 5 6 0

6
5
4
0

My try:

#!/bin/bash
k="$1"

shift

declare -i x

x=($#)

if [ $x == 0 ]
then    
        echo "give dec or incr and numbers"
        exit 1  
fi
    
arr=($*)

if [ $k == "dec" ]
then
        for i in ${arr[@]} 
        do      
                echo $i 
        done > file1sorted
        sort -nr file1sorted
        rm file1sorted
fi

if [ $k == "incr" ]
then
        for i in ${arr[@]}
        do
                echo $i
        done > file1sorted
        sort -n file1sorted
        rm file1sorted
fi

It runs well but checking if parameters are numbers doesn't work.

my output:

   324
   231
   2
   1
   a

I want it to give me an error if I put something that is not a number

  • Why are you setting `$x` to an array in `x=($#)`? – Barmar Dec 12 '22 at 14:30
  • You have two blocks of code that are identical except for the option `-r` passed to `sort`. It would be cleaner to do something like `if test "$k" = dec; then opt=-r; fi; ... sort $opt -n ...` (don't quote `$opt` here, since you don't want to pass the empty string as an argument), passing `-r` to `sort` only if decrementing. – William Pursell Dec 12 '22 at 14:31
  • 1
    You have no code that checks if the parameters are numbers. How can it "not work" if you don't even code it? – Barmar Dec 12 '22 at 14:31
  • There's no need for the `file1sorted` file. You can pipe the output of the loop to `sort`. – Barmar Dec 12 '22 at 14:33
  • You don't check anywhere that the input is numeric; having said this, what do you consider to be a number? Just a string of digits? May it have a sign? May it have spaces in it (for better readability)? May it have a decimal point? I suggest that you first define the syntax for how a number looks like, and then think about how to verify accordingly. – user1934428 Dec 12 '22 at 14:40

0 Answers0