Eject DVD on shutdown/reboot

How do I have DVD/BD eject automatically on shutdown/reboot?

This describes how to run commands on shutdown:

https://www.baeldung.com/linux/systemd-run-script-before-shutdown

The command you want to run is eject. If it does not find your drive, you will need to pass a parameter to it - usually /dev/cdrom or /dev/sr0.

EDIT: you might want to make it something like eject ; sleep 3 - just to make sure the system doesn’t cut power to the drive before it’s finished ejecting.

Step 1: Create the Ejection Script

#!/bin/bash
# /usr/local/bin/eject-dvd.sh

# Eject the DVD drive
if [ -b /dev/sr0 ]; then
    logger -t "eject-dvd" "Ejecting DVD on shutdown/logout"
    eject /dev/sr0
fi

Make it executable:

sudo chmod +x /usr/local/bin/eject-dvd.sh

Step 2: Create the systemd Service

# /etc/systemd/system/eject-dvd.service
[Unit]
Description=Eject DVD on shutdown
DefaultDependencies=false
Before=shutdown.target reboot.target halt.target

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=/usr/local/bin/eject-dvd.sh
StandardOutput=journal

[Install]
WantedBy=multi-user.target

Step 3: Enable the Service

sudo systemctl daemon-reload
sudo systemctl enable eject-dvd.service

Even Simpler Alternative - Shutdown Script

Create a script in /etc/systemd/system-shutdown/:

sudo tee /etc/systemd/system-shutdown/eject-dvd.sh << 'EOF'
#!/bin/bash
eject /dev/sr0 2>/dev/null || true
EOF

sudo chmod +x /etc/systemd/system-shutdown/eject-dvd.sh

This runs on every shutdown/reboot automatically - no need to enable anything!

Test It

# Test the script manually
sudo /usr/local/bin/eject-dvd.sh

# Check if DVD ejects (tray should open)

# To close tray if needed
eject -t /dev/sr0

Verify It Works on Shutdown

# Check logs after shutdown/reboot
sudo journalctl | grep eject-dvd