1

Inside shell script it is picking some files from UNIX directory. Sometimes when any of these file missed then throw error & shell script got failed. I need to add Exceptional Handling in shell script. Here is the below shell script where it is picking files from directory.

#!/bin/ksh
..........
while read file
do
    upd_date=$((`date +%s`-`stat -c %Y ${file}`))
    file_nm=`basename "${file}"`
    if [[ `lsof | grep "${file_nm}"` != '' || $upd_date -lt 60 ]];
    then
        log_info "Waiting for the file ${file} to complete transfer/skip"
    else
        log_info "Data file found ${file}"
    fi
done<${TEMP}/filepath
...............

exit 0

In the line upd_date=.. throwing error whenever file missed & shell script got failed. So I need to add exception handling if file missed then it will show in log & script will execute successfully.

17
  • 4
    ksh is not bash though. Paste your script at shellcheck.net for validation/recommendation. Commented Jan 4, 2023 at 15:25
  • 2
    ksh doesn't really have exception handling. Verify that $file actually expands to a valid file name before trying to use it. Commented Jan 4, 2023 at 16:07
  • 3
    while ...; do [ -f "$file" ] || continue; ...; done ? Commented Jan 4, 2023 at 16:30
  • 1
    Or just while ...; do upd_date=$( ... ) || continue (note $() vice $(())) Commented Jan 9, 2023 at 16:00
  • 1
    checking for the existence of the file and continueing seems reasonable, but I think the whole approach should be changed. Ideally, the producer (the process writing the file) would not allow any ambiguity. Write the file somewhere else and then create the final final by creating the link (hard link) only after the file is complete and will not be modified. This allows you to avoid the whole problem of checking update time. Commented Jan 12, 2023 at 22:52

1 Answer 1

1

Use continue in between while loop. continue will skip the current iteration in for, while and until loop.

#!/bin/ksh
..........
while read file
do
  [ -f "$file" ] || continue;
  upd_date=$((`date +%s`-`stat -c %Y ${file}`))
  file_nm=`basename "${file}"`
  if [[ `lsof | grep "${file_nm}"` != '' || $upd_date -lt 60 ]];
  then
    log_info "Waiting for the file ${file} to complete transfer/skip"
  else
    log_info "Data file found ${file}"
  fi
done<${TEMP}/filepath
...............

exit 0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.