Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there a command that you can run in a shell script that would detect if the CD tray is open or closed, and return 1 or 0 depending on whether it was (or something easy to interpret)?

Currently, I am executing the open command, and timing how long it takes to execute. If it is almost instant, it is open. If it takes time, it was open and is now closed.

I would like a method that doesn't involve changing the current state - just detecting it.

share|improve this question
Why do you need this? There is probably a simpler way to achieve whatever your end goal is. Do you just want to toggle the tray? – terdon Jun 15 '14 at 16:27
No, I do need to know if it is open as the aim is to be able to check, not togggle. I can toggle with eject -T. – Tim Jun 15 '14 at 16:31
up vote 6 down vote accepted

I found a nice little solution here. The C code below, minimally changed from the linked site, will return an exit code of 0 if the tray is open and 1 if it is not.

So, save this code as something (e.g. foo.c) and compile it with this command:

gcc -o trayopen foo.c

Then, copy the compiled executable, trayopen to /usr/bin:

sudo cp trayopen /usr/bin

You should no be able to do things like

trayopen /dev/sr0 && echo closed

Or, more complete:

if trayopen /dev/sr0
    echo "Tray is open."
    echo "Tray is closed."

The code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <linux/cdrom.h>

int main(int argc,char **argv) {
  int cdrom;
  int status=1;

  if (! argv[1] ){
    printf("Usage : trayopen [device]\n");
    printf("Result: Returns a 0 if the tray was open and 1 if it was closed\n");

  if ((cdrom = open(argv[1],O_RDONLY | O_NONBLOCK)) < 0) {
    printf("Unable to open device %s. Provide a device name (/dev/sr0, /dev/cdrom) as a parameter.\n",argv[1]);
  /* Check CD tray status */
  if (ioctl(cdrom,CDROM_DRIVE_STATUS) == CDS_TRAY_OPEN) {

share|improve this answer
Thankyou! Very nice, shame it isn't included in Linux / Ubuntu by default! – Tim Jun 15 '14 at 17:35

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.