温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何理解bash readarray

发布时间:2021-10-14 14:30:51 来源:亿速云 阅读:368 作者:iii 栏目:编程语言

本篇内容主要讲解“如何理解bash readarray”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何理解bash readarray”吧!

§ 0x01 起源

工作中有如下需求,要去解析一个文件的内容,但文件是json格式的,我不想使用jq。通过grep过滤出符合要求的行,然后在for循环中处理它们。 然后发现,这样实现不行。

lines=$(grep xxxx /path/to/file.json)
for line in ${lines}; do
	echo ${line}
done

grep输出的内容变成一行了。对比运行环境和ubuntu中,发现lines的内容不同。在运行环境中是一行(换行符消失了),在ubuntu是多行。换了sed之后,确认是bash实现的问题。不能去更新运行环境中bash的版本,就只能考虑其他实现方式了。

§ 0x02 readarry

查了资料之后发现readarray,一个bash的内置函数,可以实现这个需求,它还有个别名叫mapfile。个人感觉readarray更好理解一些。 它的实方式如下:

# 声明它是个列表
delcare -a lines
readarray -t lines < <(grep xxx /path/to/file.json)
for line in "${lines[@]}"; do
	echo "${line}"
done

尽管解决过程很短,readarry这种调用形式之前也见过一直不明白,为什么会是这种形式。

< <(grep xxx /path/to/file.json)

而且,两个<之间一定要有一个空格。第2个<要与小括号紧挨着。终于通过查看bash manual找到了答案。

§ 0x03 释疑

之前也查过,没有找到。这次通过<\(在man bash中搜索到了。原文如下 :

   Process Substitution
       Process substitution allows a process's input or output to be referred to using a filename.  It takes the form of <(list) or >(list).  The process list is run asynchronously, and
       its input or output appears as a filename.  This filename is passed as an argument to the current command as the result of the expansion.  If the >(list) form is used, writing to
       the file will provide input for list.  If the <(list) form is used, the file passed as an argument should be read to obtain the output of list.  Process substitution is supported
       on systems that support named pipes (FIFOs) or the /dev/fd method of naming open files.

       When available, process substitution is performed simultaneously with parameter and variable expansion, command substitution, and arithmetic expansion.

意思是说,<(cmd)这种形式是进程替换的一种形式。<(cmd)可以作为一个文件出现。它是通过命名管道实现的。它出现的地方可以用一个文件来代替。 这也是为什么它可以在 <后出现。相当于是把文件的内容重定向到前一个命令的标准输入中了。这个过程是异步的,()中的命令可能先执行完。

疑问解答:

  1. 为什么<之间要有空格?因为<(cmd)是固定形式。

  2. 第1个<是什么作用?是输入重定向,将后面的文件的描述符,重定向到前面的命令的标准输入。

  3. 如何解释echo <(ls)的输出是/proc/self/fd/11?这也验证之前的说明,<(ls)是一个文件描述符,bash里的实现应该是从文件描述符中read,然后write到前面的命令标准输入中。与文件重定向的区别是,bash会自动区分,输入的是文件描述符还是文件。文件就先打开再读,描述符就直接读。

到此,相信大家对“如何理解bash readarray”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI