0

I'm implementing a sort-function in my script, but I have trouble in doing so:

what I want to achieve is the following:

bash script --sort 44 55 1 23 44

output:

Pinging to 192.168.1.1 succes
Pinging to 192.168.1.23 failed
Pinging to 192.168.1.44 failed
Pinging to 192.168.1.55 failed

The pinging and stuff already works, I just don't know how to make a list with the arguments, sort them and (save the list) then use them in the ping command (by using for var in $SORTEDLIST do <ping-command> done.

I already had this:

    SORTEDLIST="$SORTEDLISTS $@"
    for var in $SORTEDLISTS
    do
            echo "$var"
    done | sort -n -u

The echo was just a test, but there I'll have to save the list somehow. Any ideas?

Kryptonous
  • 99
  • 1
  • 2
  • 11
  • Have you tried with `sort` before the `for` ? – ColOfAbRiX Jun 01 '15 at 13:14
  • @ColOfAbRiX The sort function needs something to sort on: it doesn't directly work on lists, so no, that won't do it. The echoed vars are now sorted, but I want to be able to put them in a sorted list. – Kryptonous Jun 01 '15 at 13:18
  • is `$SORTEDLISTS` what is in output ? – 123 Jun 01 '15 at 13:20
  • @Kryptonous In my answer I suppose that you have just the last number of the IP, the one you provide on the command line. So you can sort it and complete later the full IP. Or maybe I misunderstood the problem and/or the context – ColOfAbRiX Jun 01 '15 at 13:40
  • No, @ColOfAbRiX, you're answer is correct as well. Pity I can only choose one solution! They're both really good. Actually, yours might even be slightly better in my situation. And indeed, I only use the last number of the IP. Thanks! – Kryptonous Jun 01 '15 at 14:56

2 Answers2

3

$@ is an array (of all script parameters), so you can sort using

OIFS="$IFS" # save IFS
IFS=$'\n' sorted=($(sort -n <<<"$*"))
IFS="$OIFS" # restore IFS

and then use the result like so:

for I in "${sorted[@]}"; do
    ...
done

Explanation:

  • IFS is an internal shell variable (internal field separator) which tells the shell which character separates words (default is space, tab and newline).
  • $'\n' expands to a single newline. When the shell expands $*, it will now put a new line between each element.
  • sort -n <<< pipes the "one argument per line" to sort which sorts numerically (-n)
  • sorted=($(...)) creates a new array with the result of the command ...

See also:

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
1

This script takes the command line arguments, it splits them one per line tr ' ' '\n', sort them numerically tr ' ' '\n' and print them :

#!/bin/bash
LIST="$@"

for I in $(echo "$LIST" | tr ' ' '\n' | sort -g)
do
    echo $I
    echo "192.168.0.1.$I"
done
ColOfAbRiX
  • 1,039
  • 1
  • 13
  • 27