我的任务是上传定界文件并进行处理。一旦处理完成,我要么说它成功,要么分析失败,我需要抛出错误。我正在子脚本中逐行读取此文件,然后在主脚本中对其进行处理(因此我在读取时无法使用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
进行阅读,而不是通过head
和tail
遍历各行。就是说,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/