Lock the Mac Desktop from the Command Line
With the help of a buried menu item, we can lock the Mac OS X screen right from the Terminal. This does not log a user out, it just brings up the standard Mac OS X lock screen and login window, requiring a valid user and password before the Mac can be used again.
This is very simple to use, if you find yourself locking the Mac often with this trick you may want to make an alias for easier access.
How to Lock the Mac Screen from Terminal in OS X
Open Terminal and enter the following in a single line:
/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend
There isn’t any confirmation, the desktop is immediately locked and the lock screen appears regardless of what is currently going on with the active user account.
To make an alias, add something like the following to your profile:
alias lockscreen='/System/Library/CoreServices/"Menu Extras"/User.menu/Contents/Resources/CGSession -suspend'
For those wondering, the menu item being used is the same Fast User Switching menu that displays a user name in the upper right corner, and the lock screen shown is identical to what is summoned if one were to select “Login Window…” from that same menu.