使用for循环bash脚本逐行读取文件

OKC*_*OKC 1 bash for-loop

比方说,我有一个名为"tests"的文件,它包含

a
b
c
d
Run Code Online (Sandbox Code Playgroud)

我试图逐行读取这个文件,它应该输出

a
b
c
d
Run Code Online (Sandbox Code Playgroud)

我创建了一个名为"read"的bash脚本,并尝试使用for循环读取此文件

#!/bin/bash
for i in ${1}; do //for the ith line of the first argument, do...
   echo $i  // prints ith line
done
Run Code Online (Sandbox Code Playgroud)

我执行它

./read tests
Run Code Online (Sandbox Code Playgroud)

但它给了我

tests
Run Code Online (Sandbox Code Playgroud)

有谁知道发生了什么?为什么打印"测试"而不是"测试"的内容?提前致谢.

Gil*_*not 7

#!/bin/bash
while IFS= read -r line; do
  echo "$line"
done < "$1"
Run Code Online (Sandbox Code Playgroud)

与其他响应不同,此解决方案可以处理文件名中包含特殊字符的文件(如空格或回车符).

  • 为了完全非破坏性,做"IFS =读取-r行" - 没有"IFS ="你将失去前导/尾随空格. (3认同)

bob*_*bah 5

你需要这样的东西:

#!/bin/bash
while read line || [[ $line ]]; do
  echo $line
done < ${1}
Run Code Online (Sandbox Code Playgroud)

你在扩张后所写的内容将成为:

#!/bin/bash
for i in tests; do
   echo $i
done
Run Code Online (Sandbox Code Playgroud)

如果您仍想要for循环,请执行以下操作:

#!/bin/bash
for i in $(cat ${1}); do
   echo $i
done
Run Code Online (Sandbox Code Playgroud)