bash:脚本看到的重定向文件为“不存在”

时间:2016-11-10 10:43:20

标签: bash

我想检查最后一个命令是否有任何错误,因此将stderr重定向到文件并检查文件中的“error”字符串。(在这种情况下只有一个可能的错误。)

我的脚本如下所示:

 #aquire lock

 rm -f /some/path/err.out
 MyProgramme 2>/some/path/err.out &

 if grep -i "error" /some/path/err.out ; then
    echo "ERROR while running MyProgramme, check /some/path/err.out for error(s)"
    #release lock          
    exit 1
 fi

'如果'条件在err.out上给出错误'没有这样的文件或目录',但我可以看到该文件存在。

我错过了什么吗?任何帮助都表示赞赏。谢谢!

PS:我无法使用$检查退出代码?因为它在后台运行。

2 个答案:

答案 0 :(得分:0)

除了调用grep时可能不存在的文件外,您只需调用grep一次,它只能看到文件中当前的任何数据。 grep在文件到达结尾时不会继续读取文件,等待MyProgramme完成。相反,我建议使用命名管道作为grep的输入。这将导致grep继续从管道读取,直到MyProgramme完成为止。

#aquire lock

rm -f /some/path/err.out
p=/some/path/err.out
mkfifo "$p"
MyProgramme 2> "$p" &


if grep -i "error" "$p" ; then
   echo "ERROR while running MyProgramme, check /some/path/err.out for error(s)"
   #release lock          
   exit
fi

答案 1 :(得分:-1)

当您在后台启动add_ad_image时,@RequestMapping(value="download", method=RequestMethod.GET) public void getDownload(HttpServletResponse response) { // Get your file stream from wherever. InputStream myStream = someClass.returnFile(); // Set the content type and attachment header. response.addHeader("Content-disposition", "attachment;filename=myfilename.txt"); response.setContentType("txt/plain"); // Copy the stream to the response's output stream. IOUtils.copy(myStream, response.getOutputStream()); response.flushBuffer(); } 可能会在 MyProgramme写入(并因此创建)文件{{1}之前执行 }}。这就是为什么即使文件在您自己检查后存在,grep也找不到它。

在使用MyProgramme检查文件之前,您可以等到后台作业使用/some/path/err.out完成。