Bash文件描述符并在while循环中将printf写入文件

时间:2018-11-11 02:16:44

标签: bash logging file-descriptor io-redirection

我正在通过一本书学习bash编程,现在我正在学习有关打开文件和文件描述符的信息,但是我无法使此代码正常工作(请参阅下文),我想使用文件描述符{{1} },将低端while循环的输出写入文件4,但是在运行代码后somefile24.log为空。

以下是代码:

somefile24.log

以下是输出:

#!/bin/bash
#
# openFile.sh: print the contents of orders.txt

shopt -s -o nounset

declare LINE

exec 3< orders.txt
while read LINE <&3
do
    printf "%s\n" "$LINE"
done


echo
echo "Here is the new part of the program!"


exec 4> somefile24.log
count=1
while read LINE <&3
do
    printf "%s-----count=%d\n" "$LINE" "$count" >&4
    let count++
done
exit 0

预期输出为:

该脚本将orders.txt的内容写入somefile24.log


我尝试检查shellcheck中的代码,但没有看到问题,仅给出了以下信息:

(something78@notemDEB78)-(01:45:03)-(~/Bash_Programming_2018)
$./openFile.sh 
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something
something and something and something

Here is the new part of the program!

我尝试在命令行上进行测试:

$ shellcheck myscript

Line 10:
while read LINE <&3
      ^-- SC2162: read without -r will mangle backslashes.

Line 22:
while read LINE <&3
      ^-- SC2162: read without -r will mangle backslashes.

Line 25:
    let count++
    ^-- SC2219: Instead of 'let expr', prefer (( expr )) .

我知道我可以做到:

(something78@notemDEB78)-(01:59:41)-(~/Bash_Programming_2018)
$exec 3>somefile24.log 
(something78@notemDEB78)-(01:59:59)-(~/Bash_Programming_2018)
$echo testing >&3
(something78@notemDEB78)-(02:00:03)-(~/Bash_Programming_2018)
$cat somefile24.log 
testing

问题:

是否可以使用文件描述符在循环中写入像这样的文件?如果是,我做错了什么事情?

为什么运行脚本后while printf "%s\n" "$LINE" >> somefile24.log 总是为空?

2 个答案:

答案 0 :(得分:4)

您已经在第一个循环中读取了文件的内容。因此,文件描述符3已经在EOF上。您可以在重新读取文件描述符3之前重设它。例如。在第二个循环之前,再次运行此命令exec 3< orders.txt

答案 1 :(得分:1)

在第一个循环之后,文件描述符位于EOF。因此,在进入第二个循环之前,您需要重置文件描述符。