Lock Screen Command One-Liner
In OS X 10.9 and later:

pmset displaysleepnow


By itself, this command only causes the display to sleep, resulting in a black screen. By configuring your computer to require a password immediately after sleep, this one-liner works as a "lock computer" command. The preference is available at System Preferences > Security &amp; Privacy > General.

Source: How to lock screen on MacBook Air?