bash - using -sort in linux -


i want sort input of user sort in case (and function). never used before. have use array or something?

for example user does:

bash test.sh 50 20 35 50 

normally in script happen:

ping c -1 "192.168.0.$i" 

that results in

192.168.0.50 192.168.0.20 192.168.0.35 192.168.0.50 

now want last numbers sorted , pinged smallest biggest number this: 20 35 50 , if have 2 times same number, script pings number 1 time.

sortnumbers(){   }   ...  case  -sort ) sortnumbers;;  esac 

you can use this:

#!/bin/bash array=($(printf '%s\n' "$@"|sort -nu)) echo ${array[@]} 

if run test.sh 34 1 45 1 5 6 6 6, give output:

1 5 6 34 45 

now can use variable $array for loop like:

for in ${array[@]};do #do $i done 

explanation:

the arguments of script piped command sort , output assigned array named array. options -n numerical sort , -u unique.

assumed complete code (for clarification):

#!/bin/bash array=($(printf '%s\n' "$@"|sort -nu)) in ${array[@]};do ping -c -1 "192.168.0.$i" done 

using function:

sortnumbers(){ array=($(printf '%s\n' "$@"|sort -nu)) } sortnumbers 43 1 2 8 2 4 98 45 echo ${array[@]} ##this sample use, can put loop here 

so can declare array array=($@) @ begining of script. call sortnumbers function arguments (remember exclude -sort argument) when needed sort them (it change variable $array sorted content). put loop outside function takes whatever in variable $array (sorted or unsorted), way have way (choice sort or not).


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -