Bash 使用带管道和here字符串的内置读取

Bash 使用带管道和here字符串的内置读取,bash,pipeline,herestring,Bash,Pipeline,Herestring,我正在处理一个图片包,“文件”从中返回以下内容: $ file pic.jpg pic.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 96x96, segment length 16, baseline, precision 8, 231x288, frames 3 $ file pic.jpg | cut -d',' -f8 | tail -c+2 231x288 因此,在继续裁剪之前,我使用内置的“读

我正在处理一个图片包,“文件”从中返回以下内容:

$ file pic.jpg
pic.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 96x96, segment length 16, baseline, precision 8, 231x288, frames 3
$ file pic.jpg | cut -d',' -f8 | tail -c+2
231x288
因此,在继续裁剪之前,我使用内置的“读取”在两个变量中拾取维度

但有些事我想不通。为什么这个构造不起作用

$ ( file pic.jpg | cut -d',' -f8 | tail -c+2 | IFS=x read width height ; echo w:$width h:$height; )
w: h:
…当这个构造工作时

$ ( IFS=x read width height <<< $(file pic.jpg | cut -d',' -f8 | tail -c+2) ; echo w:$width h:$height; )
w:231 h:288

$(如果s=x read width height在bash中,管道中的命令在子shell中运行(请参阅手册的最后一段)。当子shell退出时,您在子shell中声明的任何变量都将消失

您可以使用
{}
分组构造将
读取
回显
保持在相同的子shell中:

file pic.jpg | cut -d',' -f8 | tail -c+2 | { IFS=x read width height ; echo w:$width h:$height; }

这就是为什么here字符串很有用:它在当前shell中运行
read
命令,因此变量在下一个命令中可用。

在bash中,管道中的命令在子shell中运行(请参阅手册的最后一段)。当子shell退出时,在子shell中声明的任何变量都将消失

您可以使用
{}
分组构造将
读取
回显
保持在相同的子shell中:

file pic.jpg | cut -d',' -f8 | tail -c+2 | { IFS=x read width height ; echo w:$width h:$height; }
这就是为什么here字符串很有用:它在当前shell中运行
read
命令,因此变量在下一个命令中可用。

您可以从ImageMagick使用并执行以下操作

$ identify -format 'w=%[w]; h=%[h]' file.jpg
注意
=
的用法,这样您就可以

$ eval $(identify -format 'w=%[w]; h=%[h]' file.jpg)
要设置shell中的变量,可以使用from ImageMagick和do

$ identify -format 'w=%[w]; h=%[h]' file.jpg
注意
=
的用法,这样您就可以

$ eval $(identify -format 'w=%[w]; h=%[h]' file.jpg)

要设置shell中的变量

实际上,当您使用
bash
时,有一种更简单的方法,只需要一行,无
eval
s,无
cut
s和无
tail
s:

read w h < <(identify -format "%w %h" file.jpg)

read w h<实际上,当您使用
bash
时,有一种更简单的方法,只需要一行代码,无
eval
s,无
cut
s和无
tail
s:

read w h < <(identify -format "%w %h" file.jpg)

read w h<谢谢你的提示!我的问题集中在
read
在那种情况下的使用,但是你的回答还是很有帮助的。谢谢你的提示!我的问题集中在
read
在那种情况下的使用,但是你的回答还是很有帮助的。这就抓住了重点。就像我之前写的
IFS=x
一样read
width
height
不能转发到父shell。感谢您指出这一点!这就抓住了关键点。就像我在
read
之前写的
IFS=x
一样,
width
height
不能转发到父shell。谢谢您指出这一点!它不应该是吗工作正常。你复制并粘贴了吗?在第一个
之后必须有一个spsce是的,我错误地添加了一个空格,而不是编写
<它被称为
过程替换
,在这里进行了描述…难道
<它不应该工作正常吗?你复制并粘贴了吗?在第一个
之后必须有一个spsce是的,我错误地添加了一个空格而不是w书写
<它被称为
过程替换
,在这里描述。。。