#!/bin/bash
#
# This program reads lines from a file.
#
end_of_file=0
while [[ $end_of_file == 0 ]]; do
read -r line
# the last exit status is the
# flag of the end of file
end_of_file=$?
echo $line
done < "$1"
273
为了正确的错误处理:
#!/bin/bash
set -Ee
trap "echo error" EXIT
test -e ${FILENAME} || exit
while read -r line
do
echo ${line}
done < ${FILENAME}
111
如果您需要处理输入文件和用户输入(或stdin中的任何其他内容),请使用以下解决方案:
#!/bin/bash
exec 3<"$1"
while IFS='' read -r -u 3 line || [[ -n "$line" ]]; do
read -p "> $line (Press Enter to continue)"
done
#!/usr/bin/expect
# Pass in filename from command line
set filename [ lindex $argv 0 ]
# Assumption: file in the same directory
set inFile [ open $filename r ]
while { ! [ eof $inFile ] } {
set line [ gets $inFile ]
# You could set name directly.
set name $line
# Do other expect stuff with $name ...
puts " Name: $name"
}
close $inFile
然后称之为:
yourExpectScript file_with_names.txt
1067
使用以下Bash模板应允许您一次从文件中读取一个值并对其进行处理 .
while read name; do
# Do what you want to $name
done < filename
-9
#! /bin/bash
cat filename | while read LINE; do
echo $LINE
done
9 回答
许多人发布了一个过度优化的解决方案 . 我不认为这是不正确的,但我谦卑地认为,一个不太优化的解决方案将是可取的,让每个人都能轻松理解这是如何工作的 . 这是我的建议:
为了正确的错误处理:
如果您需要处理输入文件和用户输入(或stdin中的任何其他内容),请使用以下解决方案:
基于the accepted answer和bash-hackers redirection tutorial .
在这里,我们打开文件描述符3作为脚本参数传递的文件,并告诉
read
使用此描述符作为输入(-u 3
) . 因此,我们将默认输入描述符(0)附加到终端或另一个输入源,能够读取用户输入 .我鼓励你使用
-r
标志read
代表:我引用了
man 1 read
.另一件事是将文件名作为参数 .
这是更新的代码:
使用:
如果你设置
IFS
不同,你会得到奇怪的结果 .以下(另存为
rr.sh
)读取逐行作为参数传递的文件:说明:
IFS=''
(或IFS=
)可防止修剪前导/尾随空格 .-r
防止解释反斜杠转义 .|| [[ -n $line ]]
阻止最后一行被忽略,如果它没有以\n
结束(因为read
在遇到EOF时返回非零退出代码) .运行脚本如下:
....
我把这个问题读作:
“如果我想要读取文件,我应该怎么做?我想这样做,因为当我写'用$ name做一些任务'时,我的意思是我的任务是期望命令 . ”
从期望中读取文件:
yourExpectScript:
然后称之为:
使用以下Bash模板应允许您一次从文件中读取一个值并对其进行处理 .