Bash读取命令在循环外不起作用 [英] Bash read command doesn't work outside loop

查看:93
本文介绍了Bash读取命令在循环外不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须缺少有关Bash读取命令的非常基本的内容.在shell提示符下,这无法将三个输入字段分配给相应的变量:

I must be missing something very fundamental about the Bash read command. At the shell prompt, this fails to assign the three input fields to the corresponding variables:

% echo a b c | read x1 x2 x3
% echo $x1 $x2 $x3

% 

这可以:

% echo a b c | while read x1 x2 x3 ; do
> echo $x1 $x2 $x3
> done
a b c
%

我只需要阅读一行输入即可.这里使用while循环是不正确的,因为当循环的子进程退出时,我会丢失x1,x2和x3的值.我必须将所有访问它们的代码放在循环体内(为了清晰性",可能在结尾处中断),这似乎很骇人.在if命令中使用它也可以,但是与while循环一样存在相同的子流程问题:

I only have to read one line of input. Using a while loop is incorrect here, as I lose the values of x1, x2, and x3 when the loop's subprocess exits. I'd have to place all the code that accesses them within the loop body (and perhaps break at the end, for "clarity"), which seems very hackish. Using it within an if command works as well, but suffers from the same subprocess issues as a while loop:

% echo a b c | if read x1 x2 x3 ; then echo $x1 $x2 $x3; fi
a b c
% echo $x1

BASH_VERSION报告为"4.2.45(1)-发行版".

BASH_VERSION reports as "4.2.45(1)-release".

推荐答案

问题出在管道上.从bash手册:

The problem is the pipe. From bash manual:

管道中的每个命令都作为单独的进程执行(即, 一个子外壳).

Each command in a pipeline is executed as a separate process (i.e., in a subshell).

您必须执行相反的操作,即在当前进程中调用read,并在子进程中生成输入.例如:

You have to do reverse, i.e., call read in current process and have input generated in subprocess. For example:

$ read x1 x2 x3 < <(echo a b c)
$ echo $x1 $x2 $x3
a b c

这篇关于Bash读取命令在循环外不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆