简体   繁体   中英

Linux bash scripting: sorting a list to use

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?

$@ 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM