How do I lock the screen from a terminal?

Simple:

gnome-screensaver-command -l

The following can also work, if the screensaver is set to lock when activate (see screensaver settings), since the command activates the screensaver:

gnome-screensaver-command -a

You can add an alias to the command by editing the file .bashrc (or .bash_aliases) in your home directory:

gedit $HOME/.bashrc

and adding the following line:

alias lock='gnome-screensaver-command -l'

Then from terminal:

source .profile

This will activate the alias. From now on, the alias lock in a terminal will have the effect of locking the screen.


In addition to what January said, this also works:

gnome-screensaver-command --lock

or

gnome-screensaver-command -l

According to the gnome-screensaver-command man page...

-l, --lock                 Tells the running screensaver process to lock the screen immediately
-a, --activate             Turn the screensaver on (blank the screen)

For further clarification, here is another question/answer (also by January) which describes the differences between invoking the lock and activating your screensaver:

Difference between gnome-screensaver-command -a and gnome-screensaver-command -l


Starting in Ubuntu 14.04, Unity's lock screen no longer uses gnome-screensaver. The command gnome-screensaver-command -l will still work in most cases, but see this question for exceptions.

If that command does not work (say, for instance, that gnome-screensaver is not installed), bringing up the proper Unity lock screen (not the greeter where you can switch users) can be done via this command in a terminal:

dbus-send --type=method_call --dest=org.gnome.ScreenSaver /org/gnome/ScreenSaver org.gnome.ScreenSaver.Lock