CentOS 7サーバーで自動バックアップを実行するスクリプトを作成しました。バックアップは/home/backupディレクトリに保存されます。スクリプトは機能しますが、今度はバックアップが発生した後にファイルの数を数え、数字が5を超える場合は、最も古いバックアップを削除する方法を望んでいます。
以下は私のバックアップスクリプトです。
#!/bin/bash
#mysqldump variables
FILE=/home/backup/databasebk_!`date +"Y-%m-%d_%H:%M"`.sql
DATABASE=database
USER=root
PASS=my password
#backup command process
mysqldump --opt --user=${USER} --password=${PASS} ${DATABASE} > ${FILE}
#zipping the backup file
gzip $FILE
#send message to the user with the results
echo "${FILE}.gz was created:"
ls -l ${FILE}.gz
# This is where I would like to count the number of files
# in the directory and if there are more than 5 I would like
# to delete the oldest file. Any help is greatly appreciated
ありがとう - マイク
ベストアンサー1
ループのない純粋なBashでは:
ls -t | tail -n +6 | xargs -d '\n' rm
説明する:
ls -t
現在のディレクトリ内のすべてのファイルを変更時間で並べ替え、最新のファイルから印刷します。tail -n +6
最初の5行を無視し、6行目から行を印刷します。xargs -d '\n' rm
渡されたファイルを1行に1つずつ削除します。ファイル名にスペースや引用符がないと確信している場合はxargs rm
。
これにより、ディレクトリに5つのファイルしか残らないように、必要な数のファイルが削除されます。最も古いファイルを1つだけ+6
削除するには1
。