I am trying to write a script to send an email whenever a usb device is connected to my computer (Arch Linux). The code I wrote is
#!/bin/bash
if [[ ! -z "$1" ]]; then
echo "USB inserted at $(date) for $1 and $2" >> /home/user/commands/logs.log
cd ~
ip -4 addr | grep -oP '(?<=inet\s)\d+(\.\d+){3}' > /home/user/commands/testing.txt
echo -e "Subject: Hello \n\nBody:usb inserted at $(ip -4 addr | grep -oP '(?<=inet\s)\d+(\.\d+){3}')\nthrough the mail" | msmtp [email protected]
fi
the script is supposed to send the ipv4 address to the mail. The usb insertion is being detected and the log file and testing txt file is being written.
But the mail is not being sent. I wrote the mail code separately through the terminal and it seems to be working. But inside the code, the mail is not getting run.
I have set the msmtp working. I have checked using terminal commands directly and it is working. But through the script it is not working.
All other commands are getting executed and I am getting the files.
This is my rules script
ACTION=="add",\
SUBSYSTEMS=="usb",\
ENV{DEVTYPE}=="usb_device",\
RUN+="/usr/local/bin/usbinserted.sh '%E{DEVTYPE}' '%E{DEVNAME}'"
udev
may be using root user, and the default.msmtprc
is usually in your user directory. You might need to set "default"msmtp
user to root.ch ~
when it changes to root home directory./root
and who isroot
. I added .msmtprc file in/root
msmtp
a couple of months ago.