Bash スクリプトがループを中止する

Bash スクリプトがループを中止する

次のスクリプトがあります:

#!/bin/bash -e
set -e
DATA_DIR=/home/admin/backup_avl_historico/data
DB_HOST=myHost
DB_USER=myPass

#extract table list
logger 'Extracting Table List'
psql -h $DB_HOST -U $DB_USER -c "select table_name from information_schema.tables where table_name like 'avl_historico_%';" -t -o $DATA_DIR/tables.list
array=($(wc -l $DATA_DIR/tables.list))
logger ''$array
total_tables=${array[0]}
logger 'Total tables: '$total_tables

#Get max date
max_date=$(psql -h $DB_HOST -U $DB_USER -t -c "select now() - interval '12 months'")
logger 'Max date: '$max_date

array=($max_date)
date=${array[0]}
logger 'Only date: '$date

#Dump each table
while read table_name
do
logger 'looping...'
        if [ ! -z "$table_name" ]; then
                logger 'Processing table '$table_name
                output=${table_name}_pre_${date}.csv
                psql -h $DB_HOST -U $DB_USER -t -F , -c "COPY (select * from reports.$table_name where fecha < '$max_date') TO STDOUT WITH CSV" -o ${DATA_DIR}/$output
                if [ -f ${DATA_DIR}/$output ];then
                        if test -s ${DATA_DIR}/$output
                        then
                                logger 'Deleting records'
                                psql -h $DB_HOST -U $DB_USER -c "delete from reports.$table_name where fecha < '$max_date'"
                                logger 'Gzipping '$output
                                pigz  ${DATA_DIR}/$output
                                logger 'Moving to S3'
                                aws s3 mv ${DATA_DIR}/$output.gz s3://my-bucket/avl_historico/
                                logger 'Vacuuming table'
                                psql -h $DB_HOST -U $DB_USER -c "vacuum full analyze reports.$table_name"
                        else
                                rm ${DATA_DIR}/$output
                        fi
                fi
        fi
done < $DATA_DIR/tables.list

私が抱えている問題は、PostgreSQL が次のエラーでステートメントを終了することです。

ERROR:  canceling statement due to lock timeout

スクリプト全体が中止され、doループの次の反復は続行されません。

この終了条件を回避する方法についてのアイデアがあれば、スクリプトで1回の反復をスキップして、残りの反復を続行できるようにしていただければ幸いです。

答え1

スクリプトで失敗に関係なくすべてのコマンドを実行したい場合は、両方の-eフラグを削除します。一方、エラーが発生した場合にスクリプトを終了したいが、特定のエラー (この場合は PostgreSQL) をキャッチしたい場合は、フラグの 1 つだけを残します。-eどちらでもかまいませんが、個人的な好みはスクリプトにあり、シェバンには関係ありません。エラーをキャッチする方法は、||0 以外で終了するコマンドの最後に (論理 OR) を追加することです。これは、||前のコマンドの終了コードが 0 でない場合は、次のコマンドを実行します。

psql -h $DB_HOST -U $DB_USER -c "delete from reports.$table_name where fecha < '$max_date'" || true

上記の例では、psql0 以外の終了コードを黙ってキャッチして続行します。trueコマンドは任意のものに置き換えることができます (エラーをログに記録する、しばらく待つなど)。必ず 0 で終了するようにしてください。そうしないと、同じ状況で終了します。コマンドはまったく何もtrue行わず、0 コードで終了するだけです。

関連情報