shell - 在shell脚本中如何区分读取和EOF时返回的错误

标签 shell unix error-handling ksh file-processing

我的任务是上传定界文件并进行处理。一旦处理完成,我要么说它成功,要么分析失败,我需要抛出错误。我正在子脚本中逐行读取此文件,然后在主脚本中对其进行处理(因此我在读取时无法使用ifs)。

我将重命名为.done,以防所有行被解析。现在我想知道在EOF到达之前何时出现错误,以便我可以将其重命名为.err。如果我的文件末尾没有换行符怎么办?

结构主要如下:

Main script:
Calls parent script with filepath
gets the fileName and no of line in the files, calls the Child script with a nth line no in a loop until total no of lines are reached

Parent script:
#some validations to get the txt file from the list of files
... 
fileName=`ls -A1 *.txt`
...

Child script:
...
lineno=$1
fileName=$2
noOfLines=$3
line=`tail -$lineno $fileName | head -n1`

if [ $lineno -eq $noOfLines ] 
then
    noExt="${fileName%.*}"
    mv "$fileName" "$noExt.done" #success case
fi

现在,如果文件错误或解析失败,我还需要将文件重命名为.err。
请让我知道如何捕捉错误。

最佳答案

在shell中,您使用read进行阅读,而不是通过headtail遍历各行。就是说,POSIX标准在其描述中指出:

 EXIT STATUS

  The following exit values shall be returned:
 0
       Successful completion.
>0
       End-of-file was detected or an error occurred.

这意味着您无法区分EOF和在Shell中读取时的错误。

至于其他子问题,有good reasons why files must have a trailing newline;我已经看到sed(1)在某些unixoid系统上没有作用,甚至没有剥离最后一行。

关于shell - 在shell脚本中如何区分读取和EOF时返回的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34331922/

相关文章:

linux - 我如何在 shell 中使用函数编写这个

haskell - 当输入值是Haskell中的Float类型而不是Integer类型时,如何创建错误消息

java - Tomcat 7.0.47 - Windows - 缺少未处理的异常/堆栈跟踪

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

linux - 我如何在 bash 循环中从文件中分配这些配置变量

python - 如何编写一个用 python 调用自身的 bash 脚本?

linux - 在 bash 中设置全局变量

linux - 未读取 openldap ACL

bash - 写入文件,但如果存在则覆盖它

unix - 查找我的 FreeBSD 服务器上的所有粘性位文件