Replacement for CGSession –suspend

big surcommand line

I used to cause my iMac to put up its lock screen from shell scripts. It was dead simple:

'/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession' -suspend

In MacOS Big Sur, /User.menu/ is not at that location, and I cannot find a file named CGSession. What is the equivalent command line in Big Sur? I would like to avoid using root privilege for this task.

Best Answer

User.menu is but one of many missing on macOS Big Sur, namely Battery.menu, Bluetooth.menu, Clock.menu, Displays.menu, Eject.menu, IrDA.menu, UniversalAccess.menu, User.menu, and Volume.menu.

Assuming you have not changed the system default keyboard shortcut for Lock Screen, ⌃⌘Q, the following command in Terminal will lock the screen:

osascript -e 'tell app "System Events" to key code 12 using {control down, command down}'

The first time I executed that command it failed and I was prompted with two dialog boxes, the first being:

Terminal wants access

After clicking OK, the second one was:

Accessibility Access (Events)

Clicking Open System Preferences took me to System Preferences > Security & Privacy > Privacy > Accessibility, where I clicked the check box for Terminal after unlocking the pane.

I then executed the command again in Terminal and it locked the screen.

After unlocking the screen, I then created a shell script as lockscreen in /usr/local/bin, e.g:

cd /usr/local/bin
sudo nano lockscreen

Added the following code:

#!/bin/zsh

osascript -e 'tell app "System Events" to key code 12 using {control down, command down}'

Then pressed ⌃X followed by Y and then Enter, and back a the prompt:

sudo chmod +x lockscreen

I then executed the lockscreen command and it too worked, and without having to make any additional security changes. It also works when calling it from other shell scripts.


Note: If you prefer to use a osascript shebang, instead of zsh, use the following code:

#!/usr/bin/osascript

tell application "System Events" to key code 12 using {control down, command down}