什么“<

问题描述 投票:29回答:4

当使用包含空格的文件的文件夹递归循环时,我使用的shell脚本是这种形式,从internet复制:

    while IFS= read -r -d $'\0' file; do
      dosomethingwith "$file"        # do something with each file
    done < <(find /bar -name *foo* -print0)

我想我理解IFS位,但我不明白'< <(...)'字符是什么意思。显然这里有一些管道。

你知道,谷歌“<<”非常难。

bash shell built-in
4个回答
36
投票

<()在手册中被称为process substitution,类似于管道,但传递/dev/fd/63形式的参数而不是使用stdin。

<从命令行上命名的文件中读取输入。

这两个操作符一起完全像管道一样运行,因此可以重写为

find /bar -name *foo* -print0 | while read line; do
  ...
done

5
投票

<重定向到stdin。

<()似乎是某种反向管道,如页面所述:

find /bar -name *foo* -print0 | \
while IFS= read -r -d $'\0' file; do
  dosomethingwith "$file"        # do something with each file
done

将无法工作,因为while循环将在子shell中执行,并且您将丢失循环中所做的更改


4
投票

<(命令)是进程替换。基本上,它创建一个称为“命名管道”的特殊类型的文件,然后将命令的输出重定向为命名管道。例如,假设您想要翻阅超大目录中的文件列表。你可以这样做:

ls /usr/bin | more

或这个:

more <( ls /usr/bin )

但不是这个:

more $( ls /usr/bin )

当您进一步调查时,原因就变得清晰了:

~$ echo $( ls /tmp )
gedit.maxtothemax.436748151 keyring-e0fuHW mintUpdate orbit-gdm orbit-maxtothemax plugtmp pulse-DE9F3Ei96ibD pulse-PKdhtXMmr18n ssh-wKHyBU1713 virtual-maxtothemax.yeF3Jo
~$ echo <( ls /tmp )
/dev/fd/63
~$ cat <( ls /tmp )
gedit.maxtothemax.436748151
keyring-e0fuHW
mintUpdate
orbit-gdm
orbit-maxtothemax
plugtmp
pulse-DE9F3Ei96ibD
pulse-PKdhtXMmr18n
ssh-wKHyBU1713
virtual-maxtothemax.yeF3Jo

/ dev / fd /无论是什么行为都像是一个文本文件,在括号之间输出命令。


-2
投票

<<运算符引入了here-document,它将另一个命令的输出作为第一个命令的输入。

更新

好的,所以自从我15年前上次使用它以来,它们必须在shell中添加一些东西。 请不要理会。

© www.soinside.com 2019 - 2024. All rights reserved.