33

If I am running a Pi headless, is there a command I can use to safely shut down, or should I simply remove the power cord?

Eric Wilson
  • 1,745
  • 5
  • 16
  • 14

8 Answers8

40

You can safely shutdown the pi using

shutdown -h now

The -h just halts all processes

Impulss
  • 906
  • 11
  • 18
40

Do not simply unplug the cord, as this could occasionally (perhaps, often) lead to filesystem corruption.

As Impluss says, use shutdown. I recently ran across a tip about configuring udev to trigger shutdown or reboot when a specific usb device is unplugged. This is useful if the system has become unresponsive or has lost a network connection and you can't or won't bother with plugging hid (human interface device) stuff like a keyboard into it.

There is a good, perhaps mildly outdated but well written, introduction to udev rules |here|. The basic idea is you get some information about the device via lsusb, for example:

Bus 002 Device 003: ID 0bda:8176 Realtek Semiconductor Corp. RTL8188CUS 802.11n WLAN

The third field labelled ID is the vendor and model id separated by a colon. Presuming you do not have multiple identical devices plugged in, this combination should be unique.

You can get more detailed relevant informationan via udevadm monitor --udev --property, which will report to standard out until you kill it, eg. when I unplug the teenie weenie wifi dongle from above it spits forth:

UDEV  [2834.504860] remove   /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.6 (usb)
ACTION=remove
[...]
ID_BUS=usb
ID_MODEL=802.11n_WLAN_Adapter
ID_MODEL_ENC=802.11n\x20WLAN\x20Adapter
ID_MODEL_ID=8176
[...]
ID_VENDOR=Realtek
ID_VENDOR_ENC=Realtek
ID_VENDOR_ID=0bda

Notice the ID_MODEL and ID_VENDOR fields. These are what you want to use in your udev rule. There are some outdated or incorrect sources online that suggest using ATTR fields, but these are ENV fields with regard to a "remove" event.

Create a file in /etc/udev/rules.d. This is the same regardless of distribution. The file must end in .rules and all files in this directory are processed lexicographically. I believe rules declared earlier take precedence, so using 00-my_pi.rules will keep it at the front of the line (numbers sort before letters). In it add a line like:

ACTION=="remove", ENV{ID_VENDOR_ID}=="0bda", ENV{ID_MODEL_ID}=="8176", RUN+="/sbin/shutdown -h now"

Beware == and not =. If you use the later, the criteria is meaningless. In which case you could end up with a udev rule that matches any event!

Make sure this is loaded with udevadm control --reload-rules. Now when you yank the wifi dongle out, the pi should cleanly shutdown...give it a minute to do that and you can then unplug the power (try this with a screen attached the first time). You could also use this to reboot -- see man shutdown, and, actually, the man page for all the commands mentioned here ;)

goldilocks
  • 60,325
  • 17
  • 117
  • 234
8

You may issue the following command to shutdown:

sudo init 0

And to reboot:

sudo init 6
angussidney
  • 703
  • 10
  • 21
7

My preferred method is to use sudo poweroff, which is an alias for a shutdown command that also kills power usage.

sdenton4
  • 371
  • 2
  • 4
7

While the question has been adequately answered already; my preference is different to what has been already answered.

As others have said avoid just pulling the power. My preferred commands (either as root or prepend with sudo):

To halt: halt (for Wheezy and prior this command also powers the system off; for Jessie it doesn't actually poweroff although it is safe to pull the plug once finished) halt -p; shutdown now -h or simply poweroff are required for Jessie...

To reboot: reboot

I prefer these commands as they are straight forward, easy to remember and self-evident...

Jeremy Davis
  • 266
  • 3
  • 5
4

Just to throw it in, if you are into adding a bit of hardware, you can write a small daemon to poll the GPIO pins and upon assertion of a certain pin, reboot (or shutdown) the Pi.

Also, all commands mentioned here can be ran over SSH.

Maxthon Chan
  • 1,051
  • 8
  • 14
3

I know it's 3 years after the original question. But I just got my Raspberry Pi and I'm having trouble shutting it down if I forgot to connect it to a monitor screen and it doesn't have any network connection.

I've written a small Python script to automatically shut it down within 60 seconds by plugging in a thumbdrive containing file named "pi_auto_shutdown".

Just call this script from rc.local.

I hope this helps.

shutdown_loop_delay = 60
shutdown_flag_file = 'pi_auto_shutdown'

def poll_shutdown_flag():
    """check whether a shutdown flag file in a usb drive exists"""

    ## run mount command
    ## sample mount output: "/dev/sda1 on /media/path/"
    output, error = subprocess.Popen('mount', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
    if len(error) > 0:
        log('mount error: {}'.format(error))
        return False

    ## parse mount output
    for output_line in output.split('\n'):
        output_words = output_line.split(' ')

        if len(output_words) < 3:
            continue

        if output_words[0].startswith('/dev/sd'):
            flag_file_path = os.path.join(output_words[2], shutdown_flag_file)
            if os.path.isfile(flag_file_path):
                return True

    return False

def shutdown():
    """shutdown the system immediately"""
    subprocess.Popen('sudo shutdown -h now', shell=True).communicate()

def loop_shutdown():
    while True:
        time.sleep(shutdown_loop_delay)
        if poll_shutdown_flag():
            shutdown()

loop_shutdown()
VoidMain
  • 31
  • 1
1

I ssh into my RPi box using the command

$ ssh rpi sudo poweroff

rpi is the alias for the IP Address of my RPi box and is defined in the ~/.ssh/config file.