bash/shell 多次读取 LINE

标签 bash shell stdin

我有一个 #!/bin/sh 脚本,我需要多次读取管道输入。

我迭代它的方式似乎丢弃了它,例如以下内容;

while read LINE; do
  echo "-- $LINE"
done

while read LINE; do
  echo "## $LINE"
done

调用时

find ~/Desktop | ./my.sh

产生

-- /Users/me/Desktop/some.txt
-- /Users/me/Desktop/other.txt

不是

-- /Users/me/Desktop/some.txt
-- /Users/me/Desktop/other.txt
## /Users/me/Desktop/some.txt
## /Users/me/Desktop/other.txt

如果我需要多次使用它,有没有办法保留这个输入?

谢谢。

最佳答案

您需要自己保存输入。

#!/bin/sh

i=0;
while read LINE; do
  LINES[$i]="${LINE}"
  i=$((i+1))
done

for ENTRY in "${LINES[@]}"; do
  echo "-- ${ENTRY}"
done


for ENTRY in "${LINES[@]}"; do
  echo "## ${ENTRY}"
done

示例输出:

ls /bin/b*|./test.sh
-- /bin/basename
-- /bin/bash
## /bin/basename
## /bin/bash

关于bash/shell 多次读取 LINE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17221488/

相关文章:

linux - 将 awk 变量传递给 bash 脚本

python - 如何使用 raw_input 在 python 2.7 中接收来自 stdin 的输入?

bash - 将 awk 的结果放入数组中

bash - 如何最好地包含其他脚本?

bash - 使用 bash 代码合并两个共享 PATTERN 的文本

bash - 如何在 Visual Studio 2019 中使用 git bash 终端配置文件?

bash - 使用 sed 命令解析资源 Visual Studio .rc 文件

php - 使用请求中嵌入的数据进行 POST 的 cURL 命令

go - 在 Go 中,是否可以写入控制台并读回?

java - 博士中的命令行重定向 java