3

I have below script that I get details of some IPs in a blacklist.

check.sh

blacklist_ips='
    5.56.148.140
    94.73.159.66
    113.171.224.169
    107.150.42.226
    195.159.233.44
    89.19.7.58
'

for ipx in $blacklist_ips
do
    country=`whois $ipx | grep -i country | tail -1 | awk '{print $2}'`
    hostx=`host $ipx |awk '{print $NF}'|sed "s/\.$//"`
    printf '%s %s %s' $country $ipx $hostx          
    printf '\n'
done

It works but I want to sort the output by country section.

Now I can simply go:

bash check.sh | sort -nr

and it works OK.

But I want to do the sorting before sending the result to terminal. In other words sorting should be done inside check.sh and then should be sent to terminal.

How can I achieve this in bash script?

  • 1
    change the print statements to: printf '%s %s %s\n' $country $ipx $hostx > file.txt then add sort -nr file.txt after the for loop? – clk Jul 10 '16 at 18:30
  • Thanks for the suggestion. I do not want to clutter the folder with another file. Is it possible to do it without file i/o? – NecNecco Jul 10 '16 at 18:32
  • 1
    How many IP addresses are you looking at? There's only so much a bash script variable can hold. Would simply removing the file at the end of the script work? – clk Jul 10 '16 at 18:34
  • Well the script can be used by mutliple cron jobs or scripts. So I am a bit afraid of race condition. Do not want to read output of a previous script. – NecNecco Jul 10 '16 at 18:36
8

Just change the final done to done | sort -nr

This will sort the output of the for loop via a pipe and not need temporary files.

  • Thanks Stephen for your help. How can I add conditional for done | sort -nr please? For some conditionals, I would like to run as done | sort -nrk2? I tried to convert last line of for to a if conditional but it gave syntax error. – NecNecco Jul 10 '16 at 18:47
  • 3
    Lots of ways. One simple way is to just set a variable order=nr or order=nrk2 before the for loop based on the condition, then you can do sort -$order – Stephen Harris Jul 10 '16 at 18:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.