[英]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
. ping 和其他东西已经工作了,我只是不知道如何用参数制作一个列表,对它们进行排序并(保存列表)然后在 ping 命令中使用它们(通过
for var in $SORTEDLIST do <ping-command> done
使用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). IFS
是一个内部 shell 变量(内部字段分隔符),它告诉 shell 哪个字符分隔单词(默认为空格、制表符和换行符)。$'\\n'
expands to a single newline. $'\\n'
扩展为单个换行符。 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
) sort -n <<<
管道“每行一个参数”来sort
哪个数字sort
( -n
)sorted=($(...))
creates a new array with the result of the command ...
sorted=($(...))
使用命令的结果创建一个新数组...
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 :此脚本采用命令行参数,将它们每行拆分一个
tr ' ' '\\n'
,按数字对它们进行排序tr ' ' '\\n'
并打印它们:
#!/bin/bash
LIST="$@"
for I in $(echo "$LIST" | tr ' ' '\n' | sort -g)
do
echo $I
echo "192.168.0.1.$I"
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.