Mr.
Mr.

Reputation: 37

Add exception handling when file missing in shell script

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.

Upvotes: 1

Views: 320

Answers (1)

Shahin P
Shahin P

Reputation: 367

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

Upvotes: 1

Related Questions