我试图检查附加到电子邮件的文件是否是文本文件,如果不是,则返回错误。但是在测试过程中,我提供了有效的 text.txt,它返回“无效附件”消息。
send_email()
{
message=
address=
attachment=
validuser=1
echo "Enter the email address: "
read address
echo ""
getent passwd | grep -q $address
if [ "$?" = "0" ]
then
echo -n "Enter the subject of the message: "
read message
echo ""
echo "Enter the file you want to attach: "
read attachment
attachmenttype='file $attachment | cut -d\ -f2'
if [ $attachmenttype = "ASCII" ]
then
mail -s "$message" "$address"<"$attachment"
press_enter
elif [ $attachmenttype = "cannot" ]
then
mail -s "$message" "$address"<"$attachment"
press_enter
else
echo "Invalid attachment"
press_enter
fi
else
echo "Invalid username"
press_enter
fi
}
答案1
代替
attachmenttype='file $attachment | cut -d\ -f2'
你应该写:
attachmenttype=$(file "$attachment" | cut -d' ' -f2)
看http://wiki.bash-hackers.org/syntax/expansion/cmdsubst
或得到哑剧类型:
$ file -i "$attachmenttype" | cut -d' ' -f2
text/plain;
并根据文件类型决定要对文件执行什么操作。