Making macOS behave itself

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

April 28, 2015 — October 2, 2023

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 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.

Many of these were filesystem-specific hacks, so I broke out those into a specific filesystem-specific hacks section. Others were about easing the pains of using macOS in the low-bandwidth world or macOS server and have their own respective notebooks.

The remaining tips are arranged so that the further you get down the list the longer it has been since I have needed to know it; the later ones probably don’t work on modern macOS.

1 Necessary apps

1.1 Floating a window

1.2 Fresh.app

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

1.3 Resource monitors

There are some real-time monitors that let us know if weare OOM, too hot etc.

These do not prevent problems, but at least they disambiguate problems.

1.4 Clipboard management

See Clipboard. Maccy, jumpcut, flycut

2 ⌘-tab app switcher appears on the wrong screen

We can make the task switcher appear on all monitors which is IMO what everyone apart from VJs should be doing.

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

3 Prevent locking

There are many apps, but I use Amphetamine.

5 OCR from screen

macOS supports an OCR system called Live Text which notionally means any time I can see text on the screen I should be able to copy and paste it (e.g. I should be able to use links that I see in a video chat). However, only some apps seem to support this feature, so I end up doing circuitous round trips from screenshots to supported apps. There are better ways.

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

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

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

I have also noticed Extract Text from a Screenshot with Shortcuts which might help terminal-shy people but I cannot 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 that Siri does not work on my laptop, which is weird because Siri is RIGHT THERE. Tapping out of that.

Before Live text, there were various, more onerous, options. See macos ocr script hacks via FastScripts 3

6 triald

7 Help I need to use a Windows keyboard

There are a lot of keys on this Windows keyboards that are useless to me. Macos has a fairly limited repertoire of ways for me to mutate the key assignment natively. How do I remap that Outlook button to be a Command key?

We can use hdiutil as per Technical Note TN2450: Remapping Keys in macOS 10.12 Sierra, but that involves some complicated keyboard character numbers or that we find by circuitous error-prone means.

An alternate solution 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 high level of system access, including continuous keystroke monitoring, so be careful.

8 Gatekeeper

An ongoing mess of opaque trade-off between security privacy and usability.

9 Desktop wallpaper

Various scrappy fan communities make animated wallpaper.

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

10 Meta tips

Mr Bishop’s Awesome MacOs Command Line lists how to fix a great many things from the keyboard. Previously on github, but that is now mostly a page about his grumpiness at lazy github drive-bys 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.

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

Apparently we now need to manually add country prefixes to any phone numbers in our inbox that arrive without country prefixes? Here is 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 it only works in versions of Macos before 12.1 because that is when Apple broke scripting for the Contacts app.

13 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.

14 Error beeps are laptop farts

I hate user interface beeps in general. I REALLY hate them being played promiscuously through arbitrary bluetooth devices. I have done 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 themselves, 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 on audio outputs to which they are not invited and have never been invited.

MacOS audio alerts, though 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. Ths OS is a sex pest when it comes to bluetooth devices, constantly attempting to interfere with them by non-consensual error beep interference. This is incredibly uncomfortable to be around.

Or: A macos beep is a guy who gets in the elevator with me, farts, then leaves again before the door closes. Why did that guy come here just to fart? He did not get anything out of it. Could he not have farted somewhere else? I could have tolerated him farting if he had not made it weird, but now it’s weird because he came in here and farted pointedly at me so I’m kind of obligated to be offended I guess?

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

  • Audio Profile Manager (USD5) Audio Profile manager does not do this thing. I tried. It managed other system sounds OK but apparently cannot stop system alert beeps playing from inappropriate devices. Macos will still frantically switch to whichever bluetooth device is most irritating.
  • SoundSource (USD43) I am not yet psychologically prepared to spend USD43 because something in my heart feels there must be another way.

14.1 Security

I should probably secure my mac. macOS Security and Privacy Guide.

15 Typing emoji

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

16 Why do files open when I click on them too long?

I didn’t double click, honest guv.

That would be spring loading which one can turn off.

17 ssh-agent died

alessiosavi says

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

Which worked for me. It is not ideal to require root permissions to share user keys.

influx6 asserts we can Restart SSH on Mac Terminal like this (also requiring root permission obviously):

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

18 Preview modern image formats

Warning: CVE - CVE-2023-4863 means that all WebP viewers before 2023-09-14 were insecure. Some of the below quicklook viewers are affected. Check the dates on software releases.

WebP support is available by WebPQuicklook: This app is insecure.

qlImagesize claims more features, but I have not tried it. Discontinued.

上的“iPreview - 强大好用的Quick Look扩展程序” enhances quicklook with a variety of image formats including AVIF, webp and eps.

dreampiggy/AVIFQuickLook: AVIF QuickLook plugin on macOS is free for AVIF.

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

19 Respond to model dialogue boxes without mouse

Some time I do not wish to click on buttons, and would happy press a button instead. That is disabled per default. There is a keyboard shortcut setting which enables tab-navigation. System Preferences → Keyboard → Shortcuts → Full Keyboard Access… → All Controls.

20 Trusting homebrew casks

brew install --cask NameOfCask --no-quarantine

Setting HOMEBREW_CASK_OPTS could automatically approve some apps, although then you are casting aside a useful security feature.

export HOMEBREW_CASK_OPTS="--no-quarantine"

21 Convert selected text

e.g. to upper case/lower case/HTML/markdown. There was this “services menu” technology which looked like it was going to do this for a while but that is no longer fashionable? 🤷‍♂ These days it seems one uses a third party app.

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

22 Usable scripting

Apple has shipped a slow, incomprehensible scripting language for as long as I have been aware of them. It’s called Applescript. After much time trying to persuade it to do things for me I feel comfortable asserting that using it will never save me time, although occasionally I execute a one-liner via osascript. There are some attempts to in-principle open up macOS’s scripting APIs to, e.g. javascript by jstalk or python via PyObjC but that’s a brutally low level to do things from unless you are an app developer, and the documentation is even worse (and then why not just use Swift?)

Some people seemed to have converged on the UIKit accessibility API as a reasonable interface to script.

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

Update: why not automate applescript via ChatGTP?

23 iTunes never finishes syncing my phone

It stays stuck on “importing photos”? Because you don’t use iCloud, right? For one thing, why would you voluntarily put your private photos in the hands of some notoriously secretive third party? For another, even if you wanted to, if you 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 you sync using a cable and iTunes, of course.

Except that, every couple of days, that 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 to not sync your images, so you might need to reconstruct your settings.

Do that, try again.

24 Creating GUIs for shell scripts

Various options.

25 Automatically anonymized system status

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

26 Change default shell

27 XCode

If you are reading this you are enough of a geek to need xcode. Run the following to install all of XCode or just the command line tools:

xcode-select --install

Xcode CLI breaks after every update. The current incantations to fix it are given in the following links:

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

28 Run out of file handles

Hmm, who knows how this works on 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

29 plist files are opaque binary messes

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

30 Which file is crashing/hanging $PID?

Perpetual monitoring natively:

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 what syscalls does the process actually try to do and if there are any failed ones (status is not 0)” :

sudo dtruss -p PID

Case study: distnoted and lsd.

30.1 lsd runaway CPU

Some indexing jobs can cause it to choke, e.g. application bundles. Also, a corrupted database, which may be fixed thusly:

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

30.2 distnoted runaway CPU

This is some kind of notifications daemon. I have no idea why it is out of control. It seems to be related to other processes such as certain version of flux or bartender. but 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 just don’t.

31 Bootloadey whodangle

For certain problems you need to reseat the SMC and PRAM which are formally referred to collective as the bootloadey whodangle. This seemed to break often for me. I have an inkling it is no longer a thing for modern Macs.

Symptoms include:

  • machine doesn’t boot
  • CPU fan going all the time
  • machine is pausing lots,
  • 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 off, on the built-in keyboard, press the (left side) ⇧-⌃-Option keys and the power button at the same time.
  • Reset the PRAM: Switch the computer off, then, while booting, press and hold the ⌥-⌘-P-R keys until the startup sound chimes 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.

31.1 Other boot key combos of note

Alt
offer a boot menu
C
boot up off CD/USB
⌘-R
Recovery OS
Shift
Safe mode
⌘-V
verbose mode
⌘-S
single user prompt

32 Networking from the command line

See also network hacks from som enon-mac-specific ones.

32.1 Renew DHCP lease

My previous awful router would cross if I leave the house and when I come back I try to use the same DHCP lease. But it’s a one-liner to fix.

sudo ipconfig set en0 DHCP
ipconfig getpacket en0

32.2 Notarization slowdowns

odgard notes that some things are slows in Macos 10.15+. Fixes suggested include

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

See also Jeff Johnson’s analysis.

32.3 Turning it off and on again

networksetup -setairportpower en0 off

Turn on wifi on your macbook from the macOS terminal command line:

networksetup -setairportpower en0 on

List available wifi networks from the macOS terminal command line:

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

Join a wifi network from the macOS terminal command line:

networksetup -setairportnetwork en0 WIFI_SSID WIFI_PASSWORD

Find your network interface name:

networksetup -listallhardwareports

32.4 DNS is choked up

Oh no! did you use your computer in some wacky workplace network that DNS blocks “frivolous” websites? You need to flush it.

DNS flush command keeps changing, eh?:

sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder

More generally, avoid the problem with upgraded DNS.

33 Focus stealing

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

CNET says: How to keep applications from stealing focus. But their first idea (edit application, break code signature) is not a viable idea in the modern world.

The command-line background-open still works, although if I wanted to launch apps this way I would be using Linux.

open -ga iCal

The Apple supported solution is for you to buy a faster computer.

34 Installing skype

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

35 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.

36 macOS claims it forgot my email/contacts/calendar password again

Then an hour later it forgets again again?

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

Linkdump while I sort it out again again 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 at the OS X preference panel — note if you’re already signed in but still seeing the pop-up message, you can sign out then sign back in to stop that password prompt from happening again
  4. Close System Preferences

37 Using Chromium (“open-source chrome”)

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

Anyway, here is a supplier of unsullied Chromium.

38 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

39 Time machine

39.1 precision control

tmutil is the command-line app which allows you to do proper monitoring and control of the time machine service. It includes, for example, backup statistics

There is also Time Machine editor which controlsvarious time machine settings including local snapshot, below. If you are using a oldish machine without a fast drive then this is useful.

39.2 local snapshots, mess

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

If, like me, you version everything in git, this is mostly annoying, but also I think harmless as they are self-cleaning. Nonetheless stuff did go wrong for me. I noticed that my spotlight indexing was stuck on the mobilebackups folder for some reason. Why was it even?

What Crap Is This: OSX’s Mobilebackups:

sudo tmutil disablelocal

40 Re-time stupid alarms

By default, if you use notifications from Apple Calendar, the notification for events is at 9am, right in the middle of the first meeting of the day. So you are half way through the report-back presentation about your recent conference visit, your laptop pops up RECTAL EXAMINATION TODAY.

You aren’t 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.

41 Concatenate PDFs

⚠️ Historical interest only ⚠️. If you 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 python2 script is still available but tedious to execute.

If you are, e.g. concatenating chapters of a PDF book you downloaded from e.g. Springer, then you might have the creation dates in the correct order even if they are lexicographically incorrect. In that case you 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 is some kind of problem with spaces in pathnames if I do it from a different folder.

42 Incoming