gpt4 book ai didi

Bash:在循环中从 STDIN 读取奇怪的行为

转载 作者:行者123 更新时间:2023-11-29 09:24:10 26 4
gpt4 key购买 nike

我观察到一种我不理解的行为,并希望有人对此有所了解。

我有两个脚本,都从 STDIN 读取。

从键盘读取数字序列(1 enter 2 enter 3 enter ...)

脚本 A 每次都打印“x”

#!/bin/bash

while read LINE
do
echo "x" # this happens everytime
echo $LINE # this is the only different line
done

output:

1
x
1
2
x
2
3
x
3
4
x
4
5
x
5

脚本 B 仅在第一次读取 LINE 时打印“x”

#!/bin/bash

while read LINE
do
echo "x" # this happens only the first time
awk '{print $LINE}' # this is the only different line
done

output:

1
x
2
2
3
3
4
4
5
5

谁能解释一下?

最佳答案

循环仍处于第一次迭代。 awk 正在读取所有连续的输入,而不是 read 命令。 awk 语句也不打印 shell 变量 LINE 的值,因为它没有在单引号内展开。相反,awk 发现其内部变量 LINE 未定义,并将其视为具有值 0。awk 然后打印 的值>$0,这是它从标准输入中读取的行。

关于Bash:在循环中从 STDIN 读取奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16572243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com