比方说,我有一个名为"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)
有谁知道发生了什么?为什么打印"测试"而不是"测试"的内容?提前致谢.
#!/bin/bash
while IFS= read -r line; do
echo "$line"
done < "$1"
Run Code Online (Sandbox Code Playgroud)
与其他响应不同,此解决方案可以处理文件名中包含特殊字符的文件(如空格或回车符).
你需要这样的东西:
#!/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)