# Online Bash Shell.
# Code, Compile, Run and Debug Bash script online.
# Write your code in this editor and press "Run" button to execute it.
# 準備假資料
echo "foo" > "20210615 - A.xls"
echo "bar" > "20210720 - A.xls"
echo "hello" > "20210725 - A.xls"
echo "world" > "20210803 - A.xls"
# 列出目前資料夾底下的檔案
echo "> Files in $(pwd):"
ls -1
# 印出今天日期
echo "> Current date: $(date)"
# 取得上個月的年月
last_month=$(date -d 'last month' +%Y%m)
echo "> Last month: ${last_month}"
# 設定要封存的檔案來源
# 使用find找名字開頭是${last_month},並且副檔名是.xls的檔案
archive_sources=$(find $(pwd) -name "${last_month}*.xls")
echo "> Archive sources: "
echo "${archive_sources}"
# 設定封存檔的檔名
archive_target="${last_month}.tar.gz"
echo "> Archive target: ${archive_target}"
# 開始壓縮封存
echo "> Start archive:"
tar -zcvPf "${archive_target}" -T <(echo "${archive_sources}")
# 列出封存的檔案
echo "> Archived files:"
tar -tzPf "${archive_target}"
# 驗證封存的檔案
IFS='
'
echo "> Verify archive file:"
for f in ${archive_sources}; do
echo -n "Verify '${f}': "
if cmp "${f}" <(tar -xzPOf "${archive_target}" "${f}"); then
echo "OK"
else
echo "Fail"
fi
done
unset IFS