I am writing a script that automatically copies sqlite files from my computer to a USB stick whenever the stick is inserted. It makes a new directory on the USB that takes the hostname of the computer, as I will be downloading from multiple computers.
The script is as follows:
#!/bin/bash
# Set the source folder to download from
src_dir="/home/atlas/atlas/runs/server"
Define hostname
usb_hostname=$(cat /etc/hostname)
Find USB path
usb_path=$(find /media/atlas/*/ -maxdepth 0 -type d -print -quit)
echo "USB path = $usb_path"
Set the destination
dest_dir=$usb_path$usb_hostname
Mount the USB device
sudo mount -t vfat /dev/sd?1 dest_dir
Create a directory on the USB stick
sudo mkdir -p $dest_dir
Copy the files with 'sqlite' in the extension from the source folder to the destination folder
find $src_dir -type f -iname "sqlite" -exec cp {} $dest_dir ;
Unmount the USB device
sudo umount dest_dir
The script works perfectly when I run it in terminal, however when it runs on insertion it fails on the 'find' command (line 'usb_path ='), where it returns 'No such file or directory'.
Things I have tried:
- Setting 'sleep 5' at the start of the script to allow time to mount; I've extended the time of this too with no change
- Checking permissions for the script to access the /media/atlas/ directory
- There are no errors in the syslog file
- 'atlas' is my user; if I change this to $(whoami) the script changes the path to /media/root/ and also cannot find any directory
- The USB device is mounted correctly (as I said, the script works fine from terminal)
- I've checked and the script does recognise /media/atlas, it just doesn't recognise any sub-directories
I'm at my wits end here. I can see that the problem is that when automatically run, the shell script can't find any directories within /media/atlas/ but I have no idea why. Any suggestions would be very much appreciated.
find
- but if it does get automounted, why would you want to mount it again? – steeldriver May 03 '23 at 17:26/dev/sd?1
(I understand you might have only NVME or SSD so the naming is different) but still this is not the way to go ... See for example Different behaviour of bash script in udev – Raffa May 03 '23 at 18:13To clarify, does this mean my aim here is not possible? I would like to set my computer up so that when a USB is inserted, files automatically copy from the computer to the USB. I thought a udev rule was the correct approach - such as was suggested here - https://askubuntu.com/questions/876028/how-to-auto-copy-to-removable-device - but it sounds like this circularity makes this impossible (at least via udev).
– John Tate May 04 '23 at 09:51