Bash
檢查文件是否是bash中的文本文件
我正在嘗試檢查附加到電子郵件的文件是否是文本文件,如果不是則返回錯誤。但是在測試過程中,我提供了一個有效的 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
}
代替
attachmenttype='file $attachment | cut -d\ -f2'
你應該寫:
attachmenttype=$(file "$attachment" | cut -d' ' -f2)
見http://wiki.bash-hackers.org/syntax/expansion/cmdsubst
或獲得mime-type:
$ file -i "$attachmenttype" | cut -d' ' -f2 text/plain;
並決定你想對文件做什麼取決於類型。