TechEarl

How to Toggle Dark Mode From the macOS Command Line

Toggle macOS dark mode from the terminal with one osascript line: instant, no restart. Force it on or off, read the current state, and skip the dead _HIEnableThemeSwitchHotKey trick. Plus the other Mac settings from the command line: system volume (osascript), Bluetooth (blueutil), a photo with the Mac camera (imagesnap) and your calendar (cal, icalBuddy).

Ishan KarunaratnePublished ⏱️ 22 min readUpdated
Share thisCopied
Toggle macOS dark mode from the terminal with one osascript line, set the volume, turn Bluetooth on or off, take a camera photo and read your calendar.

The command that actually toggles macOS dark mode from the terminal, instantly and with no restart, is one line of AppleScript run through osascript:

bash
osascript -e 'tell app "System Events" to tell appearance preferences to set dark mode to not dark mode'

Run it and the whole desktop flips: menu bar, Dock, Finder, and every app that respects the system appearance switch over the moment the line returns. not dark mode reads the current state and inverts it, so the same command toggles back and forth. There is no daemon to kick, no killall, no log out, and no reboot. It works on every macOS from Mojave (10.14, the release that introduced Dark Mode) through Tahoe.

If you found this page looking for the defaults write … _HIEnableThemeSwitchHotKey trick, skip it. That one does not switch the theme at all, and I explain why further down.

The same per-user, permission-gated terminal control covers the other Mac settings people go looking for a CLI for, and they are all on this page after the dark mode material: changing the system volume with osascript, turning Bluetooth on or off with blueutil, taking a photo with the Mac camera with imagesnap, and viewing your calendar from the Terminal with cal and icalBuddy.

Force it on or force it off

not dark mode is great for a toggle bound to a hotkey, but for a script you usually want to set an explicit state rather than flip whatever happens to be current. Set the boolean directly:

bash
# Force Dark
osascript -e 'tell app "System Events" to tell appearance preferences to set dark mode to true'

# Force Light
osascript -e 'tell app "System Events" to tell appearance preferences to set dark mode to false'

Setting dark mode to true is the programmatic equivalent of clicking Dark in System Settings, Appearance; false is the same as clicking Light. These are idempotent: forcing Dark when you are already in Dark does nothing and does not error, which is exactly what you want in a script that runs on a schedule.

If you would rather drive it from JavaScript for Automation (JXA) than AppleScript, the same property is reachable that way and behaves identically:

bash
osascript -l JavaScript -e 'Application("System Events").appearancePreferences.darkMode = true'

It is the same System Events bridge under the hood, so it needs the same Automation grant and flips live with no restart. Pick whichever language your tooling already speaks.

Read the current state first

When a script needs to branch on the appearance (do one thing in Dark, another in Light), read the boolean instead of guessing:

bash
osascript -e 'tell app "System Events" to tell appearance preferences to get dark mode'

It prints true if Dark is active and false if Light is. That gives you a clean conditional in a shell script without parsing a plist:

bash
if [ "$(osascript -e 'tell app "System Events" to tell appearance preferences to get dark mode')" = "true" ]; then
  echo "Dark mode is on"
else
  echo "Dark mode is off"
fi

The first run asks for permission

The first time you run any of these, macOS pops an Automation consent dialog: "Terminal wants access to control System Events." Click OK and it never asks again for that terminal app. This is TCC (Transparency, Consent, and Control) doing its job, because the script is reaching into another process to change a system setting.

If you ever click the wrong button, or a script runs but the appearance does not change, the grant lives in System Settings, Privacy & Security, Automation. Find your terminal app in that list and make sure System Events is checked underneath it. A non-interactive runner (a launchd job, a cron line, a CI step) has to be pre-authorized there once, because there is no human present to click the dialog.

One thing that bites people after a big upgrade: macOS Sequoia (15) tightened TCC, and a major OS update can drop the existing Automation grant, so a toggle that worked yesterday silently does nothing until you re-approve System Events for your terminal. If a previously-working script goes quiet right after an update, that consent list is the first place to look.

Why the _HIEnableThemeSwitchHotKey advice is wrong

A trick that circulates widely tells you to run something like this:

bash
# This does NOT toggle the theme. Do not use it.
sudo defaults write /Library/Preferences/.GlobalPreferences.plist _HIEnableThemeSwitchHotKey -bool true

It does not switch your appearance. All it does is flip a private, long-dead preference that was meant to arm a keyboard hotkey for theme switching, and that hotkey has not functioned in current macOS for years. The dead giveaway is the instruction that almost always rides along with it: "you need to restart for it to take effect." The real appearance switch is instant. Any command that claims a reboot is required is touching the wrong key, because the genuine setting (appearance preferences set dark mode, above) flips live with no restart. It also asks for sudo and writes a system-wide plist, where dark mode is a per-user setting, another sign it is aimed at the wrong place. Use the osascript line.

A reusable toggle function

If you flip appearance often, wrap the toggle in a tiny shell function in your ~/.zshrc. The te_ prefix keeps it from colliding with anything else on your path:

bash
# Toggle macOS dark/light from the shell. No sudo, no restart.
te_darkmode() {
  osascript -e 'tell app "System Events" to tell appearance preferences to set dark mode to not dark mode'
}

Then te_darkmode flips the desktop from anywhere. Bind it to a global key with a tool like skhd if you want a single keystroke that genuinely works, unlike the dead hotkey above.

No sudo, because it is a per-user setting

None of these commands need sudo. Appearance is stored per user, so changing it is something your own session is allowed to do without elevation. If you find a snippet that reaches for sudo to set dark mode, treat that as another sign it is editing the wrong thing. Your account toggling its own look is not a privileged operation, the same way setting your own system volume does not need root either.

This is the same osascript and System Events bridge that drives a lot of macOS terminal automation, including setting the desktop wallpaper from the command line. It is worth getting comfortable with, because once you can read and set one appearance toggle, the same pattern controls a long list of UI settings that have no dedicated CLI.

Change the system volume

The same osascript bridge sets the volume, with no install and no sudo (audio belongs to your own login session):

bash
osascript -e 'set volume output volume 50'

That sets output to 50 on a 0 to 100 scale, where 0 is silent and 100 is full. The change is instant and shows no on-screen volume HUD, which is what you want from a script. I keep it in a function because a meeting always seems to start while my speakers are still cranked from the night before.

Use the 0 to 100 scale, not the old 0 to 7 form

The older set volume 7 form still runs, but it is the legacy 0 to 7 scale: values above 7 clamp to maximum, so set volume 10 and set volume 7 do the same thing, and nothing in the command tells you which scale you are on.

bash
# Legacy 0 to 7 scale (still works, but avoid it):
osascript -e 'set volume 7'

# Modern 0 to 100 scale (use this):
osascript -e 'set volume output volume 100'

output volume names exactly what you are setting, and the range matches System Settings.

Mute, unmute and read the current level

Mute is a separate flag from a zero level. A muted Mac remembers its previous volume and restores it on unmute, while set volume output volume 0 goes silent without flipping the mute flag, so the next volume bump brings sound back.

bash
osascript -e 'set volume output muted true'    # mute
osascript -e 'set volume output muted false'   # unmute

The natural-language forms set volume with output muted and set volume without output muted do the same thing; I use the true/false pair because it templates cleanly from a variable. To read the level instead of setting it:

bash
osascript -e 'output volume of (get volume settings)'

osascript -e 'set v to get volume settings
"vol=" & output volume of v & " muted=" & output muted of v'

The first prints a single integer from 0 to 100. get volume settings returns a record, so the second reads the mute state in the same call, which is what a real toggle needs.

Microphone and alert volume

input volume is the microphone gain and alert volume is the system-sounds level, both on the same 0 to 100 scale:

bash
osascript -e 'set volume input volume 75'
osascript -e 'set volume alert volume 30'

Dropping the mic to 0 before a call is a faster mute than hunting for the toggle in whatever app is running. For daily use, a guarded function in ~/.zshrc turns the whole thing into vol 20:

bash
# Set macOS output volume on the 0 to 100 scale: vol 20
te_vol() {
  case "$1" in
    ''|*[!0-9]*) echo "usage: vol 0-100" >&2; return 1 ;;
  esac
  osascript -e "set volume output volume $1"
}
alias vol='te_vol'

The case guard rejects anything that is not all digits before it reaches osascript, so a typo prints a usage line instead of being interpolated into the AppleScript string.

Turn Bluetooth on or off

Bluetooth is the one setting here that osascript does not cover. The reliable route is blueutil, a small open-source CLI:

bash
brew install blueutil
blueutil -p 1        # Bluetooth ON
blueutil -p 0        # Bluetooth OFF
blueutil -p toggle   # flip whatever state it is in now
blueutil -p          # read the state: prints 1 (on) or 0 (off)

-p is short for --power. Do not reach for sudo: Bluetooth power is a per-user setting, and blueutil refuses to run as root unless you set BLUEUTIL_ALLOW_ROOT=1, so sudo blueutil -p 1 errors out rather than helping.

Why not a built-in command or a defaults hack

macOS ships one Bluetooth command, and it is read-only: system_profiler SPBluetoothDataType dumps the controller and every paired or connected device (each entry carries a Connected: Yes/No line and an address you can grep for), but it cannot change anything. The old defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 0 plus sudo killall bluetoothd recipe still circulates, but Apple moved Bluetooth state out of that plist and locked down the daemon, so on current macOS it often needs a reboot to take and on Apple Silicon frequently does nothing. blueutil talks to the private Bluetooth framework directly, which is why it still works.

List, connect and disconnect paired devices

bash
blueutil --paired       # everything your Mac has paired with
blueutil --connected    # only what is connected right now
blueutil --connect 00-11-22-33-44-55
blueutil --disconnect 00-11-22-33-44-55
blueutil --info 00-11-22-33-44-55   # connection + signal detail for one device

Each --paired line includes the device address (the xx-xx-xx-xx-xx-xx Bluetooth MAC) that the other commands take. That is how a login script grabs a specific keyboard or headphones without the menu bar. The other case that sends people looking for this is the stuck radio: when the menu-bar toggle stops responding and the mouse is frozen, blueutil -p 0 && blueutil -p 1 cycles the radio from the keyboard. A small wrapper keeps it short:

bash
te_bt() {
  case "$1" in
    on)  blueutil -p 1 ;;
    off) blueutil -p 0 ;;
    *)   blueutil -p toggle ;;
  esac
}

The Bluetooth permission gotcha

On recent macOS, especially Apple Silicon, the terminal app running blueutil may need Bluetooth access under System Settings, Privacy & Security, Bluetooth. The first toggle can prompt; a non-interactive script fails silently until the terminal is checked in that list. Toggling can also be briefly flaky right after the Mac wakes from sleep. If blueutil -p 1 seems to do nothing, check that permission entry first.

Take a photo with the Mac camera

macOS ships no built-in command for a still capture, so the camera is the one job on this page that needs an install. The cleanest tool is imagesnap, a small open-source utility by Robert Harder that grabs a frame from the built-in FaceTime camera or any attached USB webcam without opening Photo Booth:

bash
brew install imagesnap
imagesnap photo.jpg

That captures one frame from the default camera and writes it to photo.jpg in the current directory. Leave the filename off and imagesnap writes snapshot.jpg to wherever you ran it; pass an absolute path to put it somewhere specific.

List and pick a camera

A Mac often has more than one capture device: the built-in camera, an attached webcam, a phone acting as a Continuity Camera. List them, then select one by name with -d:

bash
imagesnap -l
imagesnap -d "FaceTime HD Camera" photo.jpg

The first device in the -l list is the default a bare imagesnap photo.jpg uses. The -d name has to match what -l reported, and it needs quotes because device names contain spaces (an external webcam looks like imagesnap -d "Logitech BRIO" photo.jpg).

Add a warm-up delay so the frame is not black

A camera sensor needs a moment to adjust exposure after it powers on. Capture instantly and you get a dark, sometimes fully black, frame. -w sets the warm-up in seconds (decimals allowed, so -w 1.5 works):

bash
imagesnap -w 2 photo.jpg

imagesnap already applies a default warm-up of about three seconds, so a bare imagesnap photo.jpg is usually fine. If you lowered it or your camera is slow to expose, raise -w until the frame is properly lit.

The Camera permission gap

This is the same TCC story as the Automation prompt above, with one twist that breaks scripted captures. Since macOS Mojave (10.14) the camera is gated by TCC, and a command-line tool does not get its own permission entry. It inherits the permission of the app that launched it: Terminal, iTerm, VS Code's integrated terminal, or whatever runs your script.

The first interactive run usually triggers a prompt, and clicking Allow records the grant against your terminal app. Run imagesnap from a cron job, a launchd agent, an SSH session, or a CI step before that grant exists, and there is no prompt to click. The capture fails, often quietly, and you are left with a missing or empty file and no obvious error. To fix it:

  1. Open System Settings, then Privacy and Security, then Camera.
  2. Find your terminal app in the list and turn it on. If it is not listed, run imagesnap once interactively so macOS registers it, then toggle it.
  3. Quit and reopen that terminal app so the new permission takes effect.

The app that owns the process needs the grant, not imagesnap itself; move the script to a different terminal and you authorize that one too. The green dot next to the menu bar clock lights up whenever any process uses the camera, so if imagesnap returns a frame but the dot never appeared, the capture did not reach the sensor, which usually points back at this permission gap.

Shoot a timelapse

-t fires on an interval (in seconds, decimals allowed) instead of taking one shot, writing numbered files (frame00001.jpg, frame00002.jpg, and so on) until you press Ctrl+C. Add -n to stop after a fixed number of frames:

bash
imagesnap -t 5 frame.jpg          # one frame every 5 seconds until Ctrl+C
imagesnap -t 5 -n 12 frame.jpg    # twelve frames (one minute), then exit

The Camera permission rule above applies to a timelapse run too. A slow interval gives the sensor plenty of time to settle, so a per-frame warm-up is rarely needed.

Capture a frame with ffmpeg instead

If ffmpeg is already installed, its avfoundation input captures a single frame without imagesnap:

bash
ffmpeg -f avfoundation -i "0" -frames:v 1 out.jpg

-f avfoundation selects the macOS capture backend, -i "0" is the device index (run ffmpeg -f avfoundation -list_devices true -i "" for the numbered list), and -frames:v 1 grabs exactly one video frame. The same TCC rule applies, and avfoundation can return a dark first frame for the same warm-up reason, so add -ss 1 to seek a second in if the shot is underexposed. imagesnap is the friendlier tool for a quick still; the ffmpeg form fits when you are already in an ffmpeg pipeline. To pull a still out of an existing video file instead of a live camera, see extract a thumbnail from a video with ffmpeg.

View your calendar from the Terminal

"Show my calendar in the Terminal" hides two different questions, and macOS answers them with two different tools. For a month grid (count days, check what weekday a date falls on), the built-in cal does it with no install. For your actual events, the meetings and birthdays in Calendar.app, cal cannot help at all, and you reach for icalBuddy.

cal with no arguments prints the current month with today highlighted. The forms I actually use:

bash
cal          # this month
cal -3       # previous, current, and next month side by side
cal 2026     # the whole year 2026
cal -y       # the whole current year
cal 7 2026   # July 2026: month first, then year

-3 is the one for scheduling near a month boundary. The argument order matters: cal 7 2026 is "month 7 of 2026," while a single value like cal 2026 is read as a whole year. If you get a full-year grid when you wanted one month, you left off the month number.

Week numbers with ncal

macOS also ships ncal, which prints the same data vertically (days of the week run down the left edge) and takes the same year and month arguments (ncal 2026, ncal 7 2026). The reason to reach for it is week numbers:

bash
ncal -w

-w is listed in cal's own help text, but it only works under ncal; cal -w just prints the usage message. cal and ncal are the same binary behaving differently by the name you invoke it with. The numbers are ISO 8601 weeks (the man page says so, and it shows: ncal -w 1 2021 labels the first days of January as week 53, the tail of 2020's last ISO week, before week 1 starts on Monday the 4th), so they match what most calendars and ticket systems call week numbers.

Read your real events with icalBuddy

cal and ncal are pure date arithmetic, with no connection to Calendar.app, your iCloud or Google calendars, or any event you have created. No flag fixes that. icalBuddy, a third-party tool by Ali Rantakari, reads the actual Calendar database. The Homebrew formula is hyphenated while the command is camel-cased:

bash
brew install ical-buddy
icalBuddy eventsToday        # today's events
icalBuddy eventsToday+7      # now through seven days out

The +N is general: eventsToday+1 is today and tomorrow, eventsToday+30 the month ahead. icalBuddy reads whatever Calendar.app has synced, so any account added there (iCloud, Google, Exchange) shows up with no extra configuration.

Grant the Calendars permission

The first icalBuddy run pops a dialog asking whether your terminal may access your Calendars. This is TCC again, and calendar access has been gated since macOS Mojave. Click OK, or icalBuddy returns nothing and looks broken. If you dismissed it, or a script never showed the dialog, grant it under System Settings, Privacy and Security, Calendars, by switching on your terminal app. On recent macOS releases the calendar store can also sit behind Full Disk Access, so if Calendars alone does not unblock it, add the terminal under Full Disk Access too and restart the terminal. The grant is per terminal app, so you do it once.

Read events without installing anything (osascript)

Calendar.app is scriptable, so the same osascript that flips dark mode can pull today's event titles with no Homebrew:

bash
osascript -e 'tell application "Calendar" to get summary of (every event of every calendar whose start date ≥ (current date) and start date < (current date) + 1 * days)'

It trips a different privacy gate than icalBuddy: scripting another app goes through TCC's Automation category (the same one dark mode uses), so the first run asks to let Terminal control Calendar, and a denial makes the script fail with AppleScript error -1743 rather than returning empty. It is also noticeably slower than icalBuddy, because it talks to Calendar.app over Apple events, and the AppleScript date filtering is fiddly to extend past a one-liner. For a zero-install peek it works; for anything more, icalBuddy is cleaner.

FAQ

No. The osascript … set dark mode command takes effect instantly, the moment the line returns. The whole desktop, menu bar, Dock, and every appearance-aware app switch over with no restart, no log out, and no daemon to kill. Any advice that says you must restart is using the wrong setting (the dead _HIEnableThemeSwitchHotKey key), not the real one.

Run osascript -e 'tell app "System Events" to tell appearance preferences to get dark mode'. It prints true when Dark is active and false when Light is, which is easy to test in a shell conditional without parsing a plist.

That is macOS Automation consent (TCC). Because the script reaches into another process to change a system setting, macOS prompts the first time. Click OK once and that terminal app is allowed thereafter. A non-interactive runner has to be granted access in System Settings, Privacy and Security, Automation, since no one is there to click the dialog.

No. It only enables a private, long-dead keyboard-hotkey preference and does not switch the appearance. The fact that the advice tells you to restart afterward is the tell that it is the wrong key, because the real switch is instant. Use the osascript appearance-preferences command instead.

No. Appearance is a per-user setting, so your own session can change it without elevation. If a snippet reaches for sudo to set dark mode, that is a sign it is writing a system-wide plist it should not be touching.

The modern set volume output volume form uses a 0 to 100 scale that matches System Settings. The bare legacy set volume 7 form uses an old 0 to 7 scale and clamps anything above 7 to maximum, so prefer the explicit output volume keyword.

The osascript route changes the volume directly without triggering the HUD that the keyboard volume keys show. That is usually what you want from a script, where a visible overlay would be noise.

You can read the state with the built-in system_profiler SPBluetoothDataType, but you cannot reliably toggle it. The old defaults write plus daemon-restart recipes either do nothing or need a reboot on current macOS. brew install blueutil is the route that actually flips the radio.

On recent macOS the terminal app needs Bluetooth permission under System Settings, Privacy & Security, Bluetooth, or a non-interactive run fails silently. Toggling can also be briefly unreliable right after the Mac wakes from sleep. Grant the permission and try again once the machine has fully woken. Also do not run it with sudo: blueutil refuses to run as root unless BLUEUTIL_ALLOW_ROOT=1 is set.

The camera sensor had not finished adjusting exposure when the frame was captured. Add a warm-up delay with -w, for example imagesnap -w 2 photo.jpg, and increase it until the image is properly lit. imagesnap applies a default warm-up of about three seconds, so a black frame usually means it was lowered or the camera is slow to expose.

Almost always the Camera permission. A CLI tool inherits the permission of the app that launched it (Terminal, iTerm, an SSH session, a cron job). If that app has not been granted Camera access in System Settings, Privacy and Security, Camera, the capture fails, often without an error. Grant the terminal app access, reopen it, and try again.

Not with a single built-in command. macOS ships no native CLI for a still capture, so you need imagesnap or ffmpeg. If you already have ffmpeg, ffmpeg -f avfoundation -i "0" -frames:v 1 out.jpg works; otherwise brew install imagesnap is the lightest option.

Because cal is a date calculator, not a calendar client. It draws a month grid and highlights today, but it has no link to Calendar.app or any synced account. To see real events, install icalBuddy with brew install ical-buddy and run icalBuddy eventsToday.

Use ncal -w, not cal -w. The flag is listed in cal's help but only takes effect under ncal. The week numbers it prints follow ISO 8601.

Almost always the Calendar permission. Your terminal app needs to be allowed under System Settings, Privacy and Security, Calendars. If that alone does not help on a recent macOS version, also add the terminal under Full Disk Access and restart it.

See also

Sources

Authoritative references this article was fact-checked against.

TagsmacOSdark modeosascriptAppleScriptterminalsystem volumeblueutilBluetoothimagesnapicalBuddy

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

Convert SVG to PNG from the command line with rsvg-convert, Inkscape, or ImageMagick (size, density, transparency), plus PSD to PNG with the [0] composite.

How to Convert SVG to PNG From the Command Line

Convert SVG to PNG from the command line with rsvg-convert, Inkscape, or ImageMagick. Set the output size explicitly, keep transparency, and avoid the blurry low-density trap. Plus PSD to PNG with ImageMagick's [0] composite trick.