[英]How to check if file is available before sending as email attachment
如果 shell 找不到附件,shell 是否可以發送不帶附件的電子郵件?
我如何檢查附件的可用性,以便如果它不存在,它只是不發送電子郵件?
有什么標志可以使用嗎?
RESULT=passed
FILE=/path/data/file.csv
LOG=/another/path/data/log.log
echo "Hello Team,
Please check the attached log and file." |mail -s "Result-$RESULT" -a $FILE -a $LOG somebody@sample.com
如果缺少此file.csv
,用戶將無法收到電子郵件。
您可以使用 test -f 來測試文件是否存在,因此:
test -f "$FILE" && echo "Hello Team, Please check the attached log and file." |mail -s "Result-$RESULT" -a $FILE -a $LOG somebody@sample.com
對任意數量的潛在附件的精選檢查:
#!/usr/bin/env bash
# Array of files to check and attach if available
declare -a file_list=(
/path/data/file.csv
/another/path/data/log.log
)
# Create an array for mail attachment arguments
declare -a attach_args=()
declare -- attached_files='' # Display actually attached files in the mail
declare -i attached_count=0 # Number of attached files
# Iterate attachments
for file in "${file_list[@]}"; do
# If file exist, is not empty and is readable
if [ -s "$file" ] && [ -r "$file" ]; then
# Add the proper attachment arguments to the array
attach_args+=(-a "$file")
attached_count=$((attached_count + 1))
# Add - filename and newline
attached_files+="- ${file}"$'\n'
fi
done
# Check to see if there is at least 1 attachment
if [ $attached_count -gt 0 ]; then
mail -s "Result-$attached_count" "${attach_args[@]}" somebody@example.com <<EOF
Hello Team,
Please check these ${attached_count} attached file(s):
${attached_files}
EOF
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.