2

I have this task of uploading a delimited file and processing it. Once the processing is done, I either say its successful and if parsing fails, I need to throw the error. I'm reading this file line by line in child script and then processing it in main script (so I can't use ifs while read).

I'm renaming to .done in case all lines are parsed. Now I would like to know when there is an error before EOF has reached so that I can rename it to .err. And what if I have a file without newline character at the end?

Structure is mostly as below:

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

Now I also need to rename the file to .err if its erroneous or parsing fails. How do I catch the error?

1

Use exit codes to communicate that information. If you want to follow conventions, you can use e.g, the

EX_DATAERR=65 

code to communicate a parsing error to your parent process:

Child

exit "$EX_DATAERR"

Parent

 case "$?" in  #$? is the exit code of the last exited child
              0) echo 'Child has exited succesfully';;
  "$EX_DATAERR") echo 'Child has experienced a parsing error';;
              *) echo 'Child has experienced an unknown error';;
esac

As far as error handling is concerned, the shell is like C rather than C++. It doesn't throw. Each error has to be returned by the callee (for processes by their exit codes as there's no global errno (using the filesystem for that would be clumsy) and the caller has to explicitly check for errors.

You can however do set -e in your shell to cause your shell to exit with an error if any of its children whose exit status hasn't been checked (e.g., in an if statement) returns a nonzero exit status. That's sort of like throwing an uncatchable exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.