linux - 为什么 "read"不读取命令输出的第一行?

标签 linux bash shell sh busybox

我想读取命令输出的第一行。但我收到一条空消息。

我用过

ls | read line
echo $line #nothing displayed

为什么 line 变量为空,如何解决?

以下代码有效。但我只想读第一行

ls | while read line; do 
    echo $line
done

如果无法使用 read,是否可以使用 grep、awk、sed 等其他函数来完成?

最佳答案

read 确实读取了第一行,但它是在子 shell 中执行的。但你可以这样做:

ls | { read line; 
  echo $line;
  # other commands using $line;
}
# After the braces, $line is whatever it was before the braces.

关于linux - 为什么 "read"不读取命令输出的第一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17925892/

相关文章:

linux - 如何从 SNMP 获取每秒接收和发送的数据字节数

linux - 如何在 Linux 上找到 HADOOP_HOME 路径?

linux - 默认的 Puppet 用户名和密码是什么?

linux - 如何在bash中的某些字符之间获取2个字符串

bash - 运行多个批处理文件但有异常(exception)

bash - tmux Escape 键退出服务器

c++ - 检测C++ Qt组合中的内存泄漏?

bash - 如何使用 Putty 解压当前目录中的所有 tar 文件

linux - 在双十进制 shell 脚本中打印时间

linux - 用于检测系统是 32 位还是 64 位的 Shell 脚本