I'm looking to auto copy the contents off of a disc on insert to a specified directory. It's not a DVD or cd simply one data file on every disc, would it be possible to do this with a shell script?
3 Answers
Yes Indeedy! I got interested so did some head scratching and a good deal of teeth nashing and hair pulling. Here it is:
#! /bin/bash
# Wait for a CD to be inserted then copy the contents
#
echo "CD copy, press <ctrl>C to exit"
echo "Looking for disk..."
#
# Go into a continuous loop always looking for a new CD
while :
do
####### Get the mount point of /dev/sr0 out of the mounts file
TEST=$(grep /dev/sr0 /proc/self/mounts)
####### If it doesn't exist, loop until it does with 1 second pause
if [ "$TEST" == "" ]; then
echo -ne "."
sleep 1
else
echo
############### Got it! Need to strip the mount point out of the string
TEST2=${TEST:9}
set $TEST2
TEST=$1
############### Do the copy process for the disk we found
echo "Copying from $TEST"
cp -vr $TEST/* ~/junk/
############### Eject the CD with suitable pauses to avoid any buffer problems
sleep 1
eject cdrom
sleep 2
fi
######## Still looping! Go back and wait for another CD!
done
exit()
You'll notice that the script assume that the cdrom is /dev/sr0 so if this is not the case you'll need to change it. Use the blkid command to find out what your optical device is called. The script copies everything to your home folder in a subdirectory called junk, and this directory must exist before you run the script.
I found the script ejects the cd/dvd nicely once the data is copied. If it doesn't eject and stays mounted I think it will try to copy the same disk all over again. Apart from that it's pretty self explanatory. Enjoy :-)

- 8,375
If you want to make a reaction when you insert a dvd/cd you need to write an udev rule.
You can find instructions here
Look into the section on running programs on specific events.
Using udev
rules in /etc/udev/rules.d
.
First identify the device by doing a tail -f /var/log/dmesg
. plugin then remove to identify your device.
Then use udevinfo
on the device to find the detailed information about (you'll use in writing your rule)
Add a new rule file /etc/udev/rules.d/90_CD_DVD.rules
Using the information from udevinfo
to filter just on your device.In the action
field of your new rule write the command cp /path-to-your-cd-dvd /path-to-save-your-files

- 5,950
cp sourcefile destination_file
cp /Documnets/letter.txt /Pictures/letter.txt
eject cdrom
toeject /dev/sr0/
since it was erroring out there for me. Probably because I decided to run this off of a live usb on my backup computer, instead of my regular install. – sarkstir Oct 09 '12 at 17:16