Making macOS behave itself

Things I have to do to keep my laptop running so I can google how to fix other things

2015-04-27 — 2025-09-23

Wherein the means to make macOS behave itself are enumerated, including an app to stop Music.app launching on device connection, terminal tips for Gatekeeper, OCR from screen, and Time Machine control.

computers are awful
macos
Figure 1

See also command lines it is tedious to remember for general POSIX commands.

Many of the commands mentioned here are supposed to be run as sudo root, and each may irremediably ruin your computer, your life, and soil everything you have ever loved. Then it might challenge you to a break dance battle, I dunno. Certainly, some of these commands have done some of that to me.

If any such adverse circumstance should eventuate, it will not be my responsibility. The only guarantee I provide here is that some stuff helped me at least one time.

See also filesystem-specific hacks, hacks for using macOS in the low-bandwidth world or macOS Server (defunct).

The remaining tips are arranged so that the further down the list we go, the longer it’s been since I needed them; the later ones probably don’t work on modern macOS.

1 Handy apps

1.1 Notunes

An app that prevents iTunes (or Music.app) from launching when we plug in or connect a device.

1.2 Fresh.app

An app that keeps “recently handled files” at the ready behind a keyboard shortcut. I use this dozens of times a day. See Ironic Software.

1.3 Resource monitors

There are some real-time monitors that let us know if we’re OOM (out of memory), running too hot, etc.

They don’t prevent problems, but they at least help disambiguate what’s going on.

1.4 Clipboard management

See Clipboard. Maccy, Jumpcut, Flycut

1.5 Quicklook preview

For some reason, quicklook previewers seem more security-hole prone. They tend not to have developer-signed certificates, and they tend to be abandoned, and image formats are frequently vectors for malware.

For example, CVE - CVE-2023-4863 means that all WebP viewers before 2023-09-14 were insecure.

Proceed at your own risk.

上的“iPreview - 强大好用的Quick Look扩展程序” enhances Quick Look with various image formats including AVIF, WebP, and EPS.

dreampiggy/AVIFQuickLook: AVIF Quick Look plugin on macOS is a free AVIF Quick Look plugin.

brew install avifquicklook
xattr -d -r com.apple.quarantine ~/Library/QuickLook/AVIFQuickLook.qlgenerator

1.6 Prevent screen locking

e.g. when we’re running the local jukebox. There are many apps, but I use Amphetamine.

1.7 Floating a window

2 ⌘-tab app switcher appears on the wrong screen

We can make the task switcher appear on all monitors, which I think everyone except VJs should do.

defaults write com.apple.Dock appswitcher-all-displays -bool true
killall Dock

4 OCR from screen

macOS supports an OCR system called Live Text, which means any time I can see text on the screen I should be able to copy and paste it (for example, I should be able to use links I see in a video chat). However, only some apps seem to support this feature, so I end up doing round trips from screenshots to supported apps. Sometimes alternative methods are useful.

Markus Schappi’s macOCR: Get any text on your screen into your clipboard.

# install
brew install schappim/ocr/ocr
# invoke
ocr

This works for me because I have a terminal open 100% of the time. It can be invoked by a shortcut, which is super easy.

I’ve also seen Extract Text from a Screenshot with Shortcuts, which might help terminal-shy people, but I can’t work out where to download it.

ltxlouis devised a Siri-based solution, but that just leads me to a download page for an app that claims Siri does not work on my laptop, which is weird because Siri is right there. I tapped out of that.

Before Live Text, there were more onerous options. See macOS OCR script hacks via FastScripts 3

5 triald

6 Remapping keys

a.k.a. Help — I need to use a Windows keyboard.

This Windows keyboard has a lot of keys that are useless to me. macOS offers a fairly limited set of native options for remapping keys. How do I remap that Outlook button to act as a Command key?

We can use hdiutil as described in Technical Note TN2450: Remapping Keys in macOS 10.12 Sierra, but it uses complicated keyboard character numbers that we have to find by error-prone means.

Another option is to use Karabiner Elements. This seems to solve all imaginable keyboard problems.

I do not know how trustworthy this software is, but it seems to require a high level of system access, including continuous keystroke monitoring, so be careful.

7 Desktop wallpaper

Various scrappy fan communities make animated wallpapers.

Here is a command-line app for stitching together “dynamic” (i.e. time-of-day-sensitive) wallpaper: mczachurski/wallpapper: Console application for creating dynamic wallpapers for macOS Mojave and newer Dynamic Wallpaper Club hosts a user-generated Gallery of pretty things and also instruction.

Too much effort? For pre-rolled wallpapers for the busy, see

8 Meta tips

Mr Bishop’s Awesome macOS Command Line lists how to fix many things from the keyboard. It was previously on GitHub, but that page is now mostly about his grumpiness at lazy GitHub drive-by contributors.

A sampling:

# screenshot
screencapture -T 3 -t jpg -P delayedpic.jpg
# quicklook preview
qlmanage -p /path/to/file
#Convert Audio File to iPhone Ringtone
afconvert input.mp3 ringtone.m4r -f m4af

See also Mathias Bynens and his incredible atomic dotfiles.

10 Gatekeeper

It’s an ongoing mess of opaque trade-offs between security, privacy, and usability.

10.1 Notarization slowdowns

odgard notes that some things run slowly in macOS 10.15 and later. Suggested fixes include:

sudo spctl developer-mode enable-terminal
sudo spctl --master-disable

See also Jeff Johnson’s analysis.

11 iMessage doesn’t know how country prefixes work any longer

Apparently we now need to manually add country prefixes to phone numbers in our inbox that arrive without them. Here’s a script to add country code to OS X Address Book entries:

tell application "Contacts"
    repeat with eachPerson in people
        repeat with eachNumber in phones of eachPerson
            set theNum to (get value of eachNumber)
            if (theNum does not start with "+" and theNum does not start with "61" and theNum starts with "0") then
                -- log "+61" & (get text 2 thru (length of theNum) of theNum)
                set value of eachNumber to "+61" & (get text 2 thru (length of theNum) of theNum)
            end if
        end repeat
    end repeat
    save
end tell

Note that this only works in versions of macOS before 12.1 because that is when Apple broke scripting for the Contacts app.

12 Error beeps are laptop farts

I hate user interface beeps in general. I really hate them being played promiscuously on arbitrary Bluetooth devices. I’ve tried my best to turn them off.

Figure 2: To the last I grapple with thee; from hell’s heart I stab at thee; for hate’s sake I spit my last breath at thee.

I do not want them. If they really must play, they can play on my laptop’s internal speakers, thank you very much. Even better would be the laptop speakers of someone else. Maybe a convicted criminal who needs this kind of low-level irritation as part of their state-mandated punishment? Or Apple Bluetooth devs needing operant conditioning. I particularly do not want beeps to manifest on audio outputs they are not invited to.

macOS audio alerts are rude intruders. For me, every time a new Bluetooth audio device or HDMI device is connected (or reconnects because a bird flies past or an angel sighs), macOS will use it for error beeps and miscellaneous notifications. The OS is overzealous when it comes to Bluetooth devices, constantly attempting interference with non-consensual error beep interjections. This is incredibly annoying.

Here are two apps that claim to prevent macOS from imposing its error beeps on random devices:

  • Audio Profile Manager (USD5) Audio Profile Manager doesn’t do this. I tried. It managed other system sounds okay, but it can’t stop system alert beeps from playing on inappropriate devices. macOS still switches to whichever Bluetooth device is most irritating.
  • SoundSource (USD43) I’m not prepared to spend USD43; my heart says there must be another way.

12.1 Security

macOS Security and Privacy Guide.

13 Typing emoji

As seen in typography. tl;dr Cmd Ctrl Space.

14 Why do files open when I click them for too long?

I didn’t double‑click, honest guv.

That’s spring loading, which we can turn off.

15 Respond to modal dialogue boxes without mouse

Sometimes I don’t want to click buttons; I’d happily press a key instead. That’s disabled by default. There is a keyboard shortcut setting that enables tab navigation. System Preferences → Keyboard → Shortcuts → Full Keyboard Access… → All Controls.

16 Trusting Homebrew casks

brew install --cask NameOfCask --no-quarantine

Setting HOMEBREW_CASK_OPTS could automatically approve some apps, although that means we’d be casting aside a useful security feature.

export HOMEBREW_CASK_OPTS="--no-quarantine"

17 Convert selected text

e.g. to upper case, lower case, HTML or Markdown. There used to be a “services menu” technology that looked like it would do this for a while, but that’s no longer fashionable. 🤷‍♂ These days we tend to use a third-party app.

  • Boop is pretty good, open-source and hackable.
  • Popclip has also been recommended.

18 Creating GUIs for shell scripts

Various options.

19 Automatically anonymized system status logs

e.g. for debugging or for sharing with a support person. Etrecheck.

20 Change default shell

21 Xcode

If we’re reading this, we’re geeky enough to need Xcode. Run the following to install Xcode or just the command line tools:

xcode-select --install

Xcode’s command-line tools break after every update.

The current incantations to fix it are listed in the links below:

xcodebuild -runFirstLaunch.
# or remove old CommandLineTools
# to force upgrade
sudo rm -rf /Library/Developer/CommandLineTools
sudo xcode-select --install
# or maybe
sudo xcode-select -s /Library/Developer/CommandLineTools

22 Usable scripting

Apple has shipped a slow, incomprehensible scripting language for as long as I can remember. It’s called AppleScript. After spending a long time trying to persuade it to do things, I’m comfortable saying it will never save me time, although I do occasionally run a one-liner via osascript. There are attempts to, in principle, open up macOS’s scripting APIs to, e.g., JavaScript via jstalk or Python via PyObjC, but that’s brutally low level unless we’re app developers, and the documentation is even worse. (If we’re writing apps, why not just use Swift?)

Some people have converged on the UIKit accessibility API as a reasonable scripting interface.

On this front, try Hammerspoon/Phoenix. pyatomac does the same for Python but seems designed for UI testers, not UI users. You can do it with AppleScript of course, if your heart overflows with bituminous hate.

Update: why not automate AppleScript via ChatGPT?

23 Bootloadey whodangle

For certain problems you need to reseat the SMC and PRAM, which are formally referred to collectively as the bootloadey whodangle. This used to break often for me. I suspect it’s no longer a thing for modern Macs.

Symptoms include:

  • machine doesn’t boot
  • CPU fan going all the time
  • machine pauses a lot,
  • having trouble getting laid,
  • a global geopolitical malaise is leading to the ineluctable slide of civilisation into ecosocial catastrophe.

Do these things:

  • Reset the SMC: Switch the computer off, then, while it’s off, press the (left-side) ⇧-⌃-Option keys and the power button on the built-in keyboard at the same time.
  • Reset the PRAM: Switch the computer off, then, while booting, press and hold the ⌥-⌘-P-R keys until the startup chime sounds again.
  • Build a small pyramid over your laptop from bronze and crystals. Burn some incense and your AppleCare guarantee in a brazier atop it. Surround it with small pictures of your departed ancestors. Make an offering of fruit and prayer.

23.1 Other boot key combos of note

Alt
Show a boot menu
C
Boot from CD/USB
⌘-R
Recovery OS
Shift
Safe mode
⌘-V
Verbose mode
⌘-S
Single-user prompt

24 Networking from the command line

See also network hacks for some non-mac-specific ones.

24.1 Renew DHCP lease

My previous awful router would get cross if I left the house and then tried to reuse the same DHCP lease when I returned. But it’s a one-liner to fix.

sudo ipconfig set en0 DHCP
ipconfig getpacket en0

24.2 Turning it off and on again

networksetup -setairportpower en0 off

Let’s turn on Wi‑Fi on our MacBook from the macOS Terminal command line:

networksetup -setairportpower en0 on

List available Wi‑Fi networks from the macOS Terminal:

/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport scan

Join a Wi-Fi network from the macOS Terminal command line:

networksetup -setairportnetwork en0 WIFI_SSID WIFI_PASSWORD

Let’s find our network interface name:

networksetup -listallhardwareports

24.3 DNS is choked up

Oh no! Did we use our computer on some wacky workplace network that blocks “frivolous” websites? We need to flush the DNS cache.

DNS flush command keeps changing, eh?:

sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder

More generally, avoid this problem with upgraded DNS.

25 Focus stealing

Stop stealing focus from me, slow app — I clicked on you about 30 seconds ago.

CNET says: How to keep applications from stealing focus. But their first suggestion — edit the application and break its code signature — isn’t viable in the modern world.

The command-line background-open still works, but if I wanted to launch apps that way I’d be using Linux.

open -ga iCal

Apple’s supported solution is to buy a faster computer.

26 Time Machine

26.1 Precision control

tmutil is the command-line app that lets us properly monitor and control the Time Machine service. It includes, for example, backup statistics.

There’s also Time Machine Editor which controls various Time Machine settings, including local snapshots (below). If we’re using an older machine without a fast drive, this is useful.

26.2 Local snapshots, mess

I think this is largely cosmetic, but macOS keeps a local copy of various versions of our files around, called local snapshots or mobile backups, depending on where you look.

If, like me, I version everything in git, it’s mostly annoying but harmless, since the snapshots are self-cleaning. Nonetheless, things did go wrong for me. I noticed that my Spotlight indexing was stuck on the mobilebackups folder for some reason. Why was it even indexing that?

What Crap Is This: macOS’s Mobilebackups:

sudo tmutil disablelocal

27 Using Chromium (“open-source Chrome”)

Harder than it should be; Google really wants us to use their furtively modified alternate branch, Google Chrome.

Anyway, here is a supplier of unsullied Chromium.

28 Reset semaphores

I can’t even remember why I needed to do this or how I worked it out, but geez — it saved my bacon from something or other.

ipcs -s | grep " 0x" | awk '{ print $2; }' | xargs -n 1 ipcrm -s

29 ssh-agent died

alessiosavi says

sudo launchctl unload /System/Library/LaunchDaemons/ssh.plist
sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist

That worked for me. It’s not ideal to require root permissions to share user keys.

influx6 asserts that we can Restart SSH on Mac Terminal like this; it also obviously requires root permissions:

sudo launchctl stop com.openssh.sshd
sudo launchctl start com.openssh.sshd

30 Dock disconnects hard drives when Mac sleeps

Thunderbolt 3 dock disconnects when MacBook sleeps:

Given that the computer sleep seems to be the problem, I turned off the “Power Nap”, and it seems to be working for me now.

  • System Preferences > Energy Saver
  • Power Adapter tab
  • Uncheck “Enable Power Nap while plugged into a power adapter

or

  1. Open System Preferences.
  2. Click the Energy Saver icon.
  3. By default the ‘Put hard disks to sleep when possible’ option will be selected. Uncheck this option.

31 iTunes never finishes syncing my phone

It stays stuck on “importing photos”? Because we don’t use iCloud, right? For one thing, why would we voluntarily put our private photos in the hands of some opaque third party? For another, even if we wanted to, if we live in a bandwidth-poor country, iCloud sync is not just bad, it’s comedically bad — atrociously, OS-floggingly slow and glitchy. “iClod”, let us call it. So we sync using a cable and iTunes, of course.

Except that every couple of days, it breaks. Here’s how to fix it. (Note that this question refers to “iPhoto”, but the same bug has been faithfully carried over and reproduced in Aperture and Photos by diligent Apple devs, and the same fix works.)

Quit iTunes.

rm -rf ~/Pictures/Photos\ Library.photoslibrary/iPod\ Photo\ Cache/

Note that this will reset iTunes so it no longer syncs our images; we might need to reconstruct our settings.

Do that, then try again.

32 Running out of file handles

Hmm — who knows how this works in the latest versions?

But the traditional advice is:

ulimit -S -n 2048

Wilson Mar says:

wget https://github.com/wilsonmar/mac-setup/raw/master/configs/limit.maxproc.plist https://github.com/wilsonmar/mac-setup/raw/master/configs/limit.maxfiles.plist

33 plist files are opaque binary messes

This is how to convert them to text. If we regard XML as text.

34 Which file is crashing/hanging $PID?

We monitor continuously by default:

fs_usage $PID | grep /path/to/file

Or the classic Unix way:

lsof -r -p $PID | grep /path/to/file

See here for some tips on debugging runaway/hung/exploded processes. “See which syscalls the process actually attempts and whether any of them fail (status is not 0)”:

sudo dtruss -p PID

Case study: distnoted and lsd.

34.1 lsd runaway CPU

Some indexing jobs can make the CPU run away, for example when processing application bundles. Also, a corrupted database can cause this; it may be fixed as follows:

/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister \
  -kill -r -domain local -domain system -domain user ; killall Dock

34.2 distnoted runaway CPU

This is some kind of notification daemon. I have no idea why it’s out of control. It seems to be related to other processes, such as a certain version of Flux or Bartender. However, the problem only seems to occur when my backup drive is plugged in. Hmmph. File a ticket?

Michael Rourke suggests doing this every minute:

#!/bin/sh

# check for runaway distnoted, kill if necessary

PATH=/bin:/usr/bin
export PATH

ps -reo '%cpu,uid,pid,command' |
    awk -v UID=$UID '
    /distnoted agent$/ && $1 > 100.0 && $2 == UID {
        system("kill -9 " $3)
    }
    '

But note this will break backup, so maybe we shouldn’t.

35 Concatenate PDFs

⚠️ Historical interest only ⚠️. If we don’t have a pre-2020 macOS, use a mainstream PDF editor.

gotofritz says:

"/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py" \
  -o PATH/TO/YOUR/MERGED/FILE.pdf \
  /PATH/TO/ORIGINAL/1.pdf \
  /PATH/TO/ANOTHER/2.pdf \
  /PATH/TO/A/WHOLE/DIR/*.pdf

UPDATE: Now that Python no longer ships with macOS, this Python 2 script is still available but tedious to execute.

If we’re, e.g. concatenating chapters of a PDF book we downloaded from e.g. Springer, then we might have the creation dates in the correct order even if they’re lexicographically incorrect. In that case we want (fish shell style)

pushd PATH/TO/PDFS
"/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py" \
  -o PATH/TO/YOUR/MERGED/FILE.pdf \
  (ls -rUt)

There’s a problem with spaces in pathnames when I run it from a different folder.

36 Installing Skype

Never install Skype! Skype is spookware. If you must use it, use the web version. UPDATE: Is MS Teams built on Skype?

37 Stop gamed and other processes leaking your data and wasting precious network sockets for no reason

Binary Bob says:

sudo defaults write /System/Library/LaunchAgents/com.apple.gamed disabled -bool true

or:

launchctl unload -w /System/Library/LaunchAgents/com.apple.gamed.plist

In reference to this.

38 macOS claims it forgot my email, contacts and calendar password again

Then an hour later it forgets again?

Woe! I fixed this once, then I forgot how I did it.

Link dump while I sort it out again:

Continuous [sic] request for the CalDAV password? Here’s one solution:

  1. Go to the  Apple menu and choose System Preferences.
  2. Choose the ‘iCloud’ preference pane.
  3. Sign in to iCloud in the preference panel — Note: if you’re already signed in but still seeing the pop-up, sign out, then sign back in to stop that password prompt from happening.
  4. Close System Preferences.

39 Re-time stupid alarms

By default, if we use notifications from Apple Calendar, the event reminder is at 9am, right in the middle of the first meeting of the day.

So we’re halfway through the report-back presentation about our recent conference visit when our laptop pops up: RECTAL EXAMINATION TODAY.

We’re not supposed to be able to change this because the thought of this cruelty is all that gets jaded Apple executives out of bed in the morning, but there is a hack they forgot to stop.

40 Incoming