在执行bash脚本期间出现命令提示符

时间:2013-08-01 16:48:50

标签: bash shell unix tee

这是我使用的脚本的简化版本: 在简化版本中,tt应该逐行读取文件input,然后将其打印到标准输出并写入文件log

input档案:

asas
haha
asha
hxa

脚本(名为simple):

#!/bin/bash

FILE=input
logfile="log"

exec > >(tee "$logfile")   # redirect the output to a file but keep it on stdout
exec 2>&1

DONE=false
until $DONE; do
read || DONE=true
  [[ ! $REPLY ]] && continue                      #checks if a line is empty

  echo "----------------------"

  echo $REPLY

done < "$FILE"
echo "----------------------"
echo ">>> Finished"

输出(在控制台上):

-bash-3.2$ ./simple
-bash-3.2$ ----------------------
asas
----------------------
haha
----------------------
asha
----------------------
hxa
----------------------
>>> Finished

此时我需要按Enter键终止脚本。请注意,执行期间出现了命令提示符-bash-3.2$

我检查过这些行应该归咎于:

exec > >(tee "$logfile")   # redirect the output to a file but keep it on stdout
exec 2>&1

没有它们,输出就像预期的那样:

-bash-3.2$ ./simple
----------------------
asas
----------------------
haha
----------------------
asha
----------------------
hxa
----------------------
>>> Finished
-bash-3.2$

更重要的是,我不需要按Enter键来终止脚本。 不幸的是,我需要将输出保存到控制台(stdout)和日志文件。

如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

如果您只需要暂停并等待用户输入,请使用pause命令:

 pause

答案 1 :(得分:1)

您可以直接在回声线上使用tee

例如:

[ben@lappy ~]$ echo "echo and save to log" | tee -a example.log
echo and save to log
[ben@lappy ~]$ cat example.log 
echo and save to log

-a的{​​{1}}参数将附加到日志中。

答案 2 :(得分:1)

正在发生的事情是tee "$logfile"异步运行。当您使用类似的进程替换时,主脚本不会等待进程退出。

所以until循环运行,主脚本退出,shell打印提示,然后tee打印输出。

您可以通过以下方式更轻松地看到这一点:

echo Something > >(sleep 5; cat)

您将收到命令提示符,然后5秒后将出现Something

几年前comp.unix.shell中有一个关于此行为的帖子。见here