3
用shell实现队列操作
source link: https://houye.xyz/2018-05/shelllist/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
用shell实现队列操作
用shell实现队列操作
最近需要在shell中实现一个FIFO的队列,折腾了一会成果大致如下。
首先实现队列的入队操作,假设从标准输入得到数据,如果当前队列为空,则把数据赋给队列,如果队列非空,则把数据加到队列的最右边,数据之间用逗号分隔(假设数据中不含有逗号),代码如下:
#!/bin/bash list=() while read line do #忽略空白字符的输入 if [ -z "$line" ];then continue fi if [ -z "$list" ];then list=("$line") else list=("${list[@]}","$line") fi done echo "$list"
下面就是出队列的操作,如果$list中没有逗号,那么$list中就只剩一个值了,此时取出$list中所有内容。如果$list中有多个值,则取左边的值并将$list中最左值出列。关于倒数第4,5行的变量取用可以参考 【Shell】变量的取用、删除、取代与替换
while [ -n "$list" ] do i=`expr index "$list" ,` if [ $i -eq 0 ];then j=$list list=() else j=${list%%,*} list=${list#*,} fi echo $j done
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK