我有以下。txt文件:

Marco
Paolo
Antonio

我想逐行读取它,对于每一行,我想为一个变量分配一个.txt行值。假设我的变量是$name,流是:

读取文件的第一行 分配$name = "Marco" 使用$name执行一些任务 从文件中读取第二行 指定$name = "Paolo"


当前回答

许多人发布了一个过度优化的解决方案。我不认为这是不正确的,但我谦虚地认为,一个不那么优化的解决方案将是可取的,以使每个人都能轻松地理解这是如何工作的。以下是我的建议:

#!/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"

其他回答

使用下面的Bash模板应该允许您一次从文件中读取一个值并处理它。

while read name; do
    # Do what you want to $name
done < filename

许多人发布了一个过度优化的解决方案。我不认为这是不正确的,但我谦虚地认为,一个不那么优化的解决方案将是可取的,以使每个人都能轻松地理解这是如何工作的。以下是我的建议:

#!/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"
#! /bin/bash
cat filename | while read LINE; do
    echo $LINE
done

正确的错误处理:

#!/bin/bash

set -Ee    
trap "echo error" EXIT    
test -e ${FILENAME} || exit
while read -r line
do
    echo ${line}
done < ${FILENAME}

如果你需要同时处理输入文件和用户输入(或者来自stdin的任何东西),那么使用以下解决方案:

#!/bin/bash
exec 3<"$1"
while IFS='' read -r -u 3 line || [[ -n "$line" ]]; do
    read -p "> $line (Press Enter to continue)"
done

基于已接受的答案和bash-hackers重定向教程。

在这里,我们打开作为脚本参数传递的文件的文件描述符3,并告诉read使用这个描述符作为输入(-u 3)。因此,我们将默认的输入描述符(0)附加到终端或其他输入源,能够读取用户输入。