What Is the Mac OS X Terminal Command to Log Out the Current User?

I would like to run something like "sleep 3600; logout", but the logout bash command only closes the current terminal. How do I close the full Mac OS X session?


Solution 1:

The following Applescript will logout the current user:

tell application "System Events" to log out

You can wrap this up in a bash alias using the osascript command:

alias maclogout="osascript -e 'tell application \"System Events\" to log out'"

It is the same as clicking " > Log out [username]...", and will logout after a 2 minute wait

This is easily combined with the sleep command:

alias delayedlogout="sleep 3600; maclogout"

..or could be combined into a single alias:

alias delayedlogout="sleep 3600; osascript -e 'tell application \"System Events\" to log out'"

Solution 2:

There is no "nice" way to log the current user out from Terminal in OS X. The 'messy' way of doing it is to kill that user's loginwindow process. It will rudely kill all processes (programs) running under your username.

Doing this is a two-step process.

  1. In terminal, run this:

    ps -Ajc | grep loginwindow
    
  2. Then, run

    sudo kill <pid>
    

    Where <pid> is the first number (second column) from the output from the above command.

Use sudo kill -9 to force kill the process which I had to do to get this to work.

So for example, when if the output to the first command is:

joshhunt    41     1    41 5e15c08    0 Ss     ??    3:13.09 loginwindow

Then I would run sudo kill 41, enter my password, and then I am logged out.

This can be combined into an bash alias:

alias messylogout="ps -Ajc | grep loginwindow | grep -v grep | awk '{print \$2}' | sudo xargs kill"

Solution 3:

I know this is an old question but it helped me, the command I needed on OS X 10.8 is:

ps -Ajc | grep loginwindow | awk '{print $2}' | sudo xargs kill -9

The awk statement is different and the kill -9 ensures the login prompt is shown.

Solution 4:

I think I have found the answer to how to Gracefully Logout of Mac OS X without the 2 minute wait.

I figured out that holding Shift, Option, and Command and pressing "q" will log out gracefully and not ask "if you want to log out".

So I coded an AppleScript through Automator to:

tell application "System Events"
     keystroke "q" using {command down, shift down, option down}
end tell

Solution 5:

I would argue that the "nicest" way post OS X 10.9 might be launchctl gui/$(id -u <username>) bootout

The post OS X 10.9 documentation for launchctl is found by running launchctl help, but essentially the command above will teardown a user's temporary session. The alternative launchctl user/$(id -u <username>) bootout tears down the permanent session that runs user daemons while the user isn't logged in.

This can be tested by running launchctl gui/$(id -u) bootout, this will immediately log you out and cause the system to display the login window (with some delay).