LoginSignup
1
2

More than 5 years have passed since last update.

SFTPサーバ上ファイル存在チェックスクリプト

Last updated at Posted at 2017-10-27

EmbulkでSFTPサーバ上のファイルを読み込む際、ファイルがなくてもエラーにならないので、事前にチェックすることにした
SFTPサーバへのログインが鍵認証である前提
環境変数でリトライ回数・間隔を指定可能

関連:
https://qiita.com/pilot/items/43ae966608861d8a7d92
https://qiita.com/pilot/items/3014910fee5dce0ce3e3

check_sftp_file_exists.sh
#!/bin/bash

if [ $# -ne 7 ]; then
  echo "Usage: $0 host port user key_file work_dir dir file" >&2
  exit 1
fi

host=$1
port=$2
user=$3
key_file=$4
work_dir=$5
dir=$6
file=$7

myname=`basename $0 .sh`
cmdfile=${work_dir}/${myname}_$$.txt
resultfile=${work_dir}/${myname}_result_$$.txt

retry_count=${RETRY_COUNT:-5}
retry_unit_seconds=${RETRY_UNIT_SECONDS:-10}
#echo retry_count=${retry_count}, retry_unit_seconds=${retry_unit_seconds} # for debug

echo "ls ${dir}" > ${cmdfile}

count=1
while :
do
  sftp -o Port=${port} -o IdentityFile=${key_file} -o StrictHostKeyChecking=no -b ${cmdfile} ${user}@${host} > ${resultfile}
  status=$?
  if [ ${status} -eq 0 ]; then
    rm -f ${cmdfile}
    break
  fi
  if [ ${count} -eq ${retry_count} ]; then
    echo Retry over >&2
    rm -f ${cmdfile} ${resultfile}
    exit 1
  fi
  sleep_seconds=$((count * retry_unit_seconds))
  count=$((count + 1))
  echo Retry after ${sleep_seconds} seconds, next count is ${count} >&2
  sleep ${sleep_seconds}
done

grep -w ${dir}/${file} ${resultfile} > /dev/null
status=$?
rm -f ${resultfile}

if [ ${status} != "0" ]; then
  echo "File not found: "${dir}/${file} >&2
  exit 1
fi

echo "File found: "${dir}/${file}

exit 0
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2