bash 哪里记录了语法“while IFS= read line”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6830735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:27:08  来源:igfitidea点击:

Where is the syntax `while IFS= read line` documented?

bashshell

提问by nachocab

Why does every example I see have while IFS= read lineand not while IFS=; read line?

为什么我看到的每个例子都有while IFS= read line而没有while IFS=; read line

I thought that name=value commandmight set a local variable but sentence="hello" echo $sentencedoesn't work, while sentence="hello"; echo $sentencedoes.

我认为这name=value command可能会设置一个局部变量但sentence="hello" echo $sentence不起作用,而sentence="hello"; echo $sentence确实如此。

回答by Jan Hudec

The:

这:

name=value command

syntax sets the nameto valuefor the command. In your example:

语法设置namevaluecommand。在你的例子中:

$ sentence="hello" echo $sentence

the $sentence is expanded by the calling shell, which does not see the setting. If you do

$sentence 由调用 shell 扩展,它看不到设置。如果你这样做

$ sentence="hello" sh -c 'echo $sentence'

(note the single quotes to have the $expanded by the called shell) it will echo hello. And if you try

(注意单引号$由被调用的外壳扩展)它将 echo hello。如果你尝试

$ sentence="hello"; sh -c 'echo $sentence'

it will not echo anything, because sentenceis set in the current shell, but notin the called one, since it was not exported. So

它不会回显任何内容,因为它sentence是在当前 shell 中设置的,而不是在被调用的shell中,因为它没有被导出。所以

IFS=; read line

will notwork, because readwill notsee the IFSsetting.

无法工作,因为read不会看到IFS设置。

回答by e.dan

Prefixing a command with parameter assignment affects the environmentof the command being executed.

使用参数分配给命令添加前缀会影响正在执行的命令的环境

In man bash:

man bash

The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described above in PARAMETERS. These assignment statements affect only the environment seen by that command.

任何简单命令或函数的环境都可以通过在其前面加上参数分配来临时扩充,如上面参数中所述。这些赋值语句仅影响该命令看到的环境。

In your example: sentence="hello" echo $sentence, sentencewill be in the environment of the echocommand (try this to show yourself: sentence=HI env | fgrep sentence), but not in the shell from which you are calling it, which would be required to pass it as an argument to echoas you are attempting.

在您的示例中:sentence="hello" echo $sentence,sentence将在echo命令的环境中(尝试这样做以显示您自己:)sentence=HI env | fgrep sentence,但不在您从中调用它的 shell 中,这将需要在echo您尝试时将其作为参数传递给。