Mac OS
The best OS a parent's money can buy
Keyboard Shortcuts
What you'll see below is incomplete, for up to date information, check Apple's documentation on keyboard shortcuts. Dan Rodney's compilation is a great source as well.
Finder
| Shortcut | Function |
|---|
| ⌘ ⌫ | Send file to trash |
| ⌥ ⌘ ⌫ | Completely delete a file |
| ⌥ ⌘ ⇧ ⌫ | Empty the trash |
| ⌘ ⇧ N | Create a new folder |
| ⌥ ⌘ V | Transfer copied file/folder to the current folder |
| ⌘ ⇧ . | Show hidden files/folders |
| ⌘ E | Eject selected disk/drive |
Navigation
| Shortcut | Function |
|---|
| ⌘ ⇧ ] | Switch to the next tab |
| ⌘ ⇧ [ | Switch to the previous tab |
| ⌘ ] | Go forward to the next page |
| ⌘ [ | Go back to the previous page |
| ⌘ ` | Switch to the previous windows of frontmost application |
| ⌘ ⇥ | Switch to the previous frontmost application |
| ⌃ ↓ | View all open windows for the current frontmost application |
| ⌃ ↑ | View all windows for all open applications |
Document Editing
These work when editing text using Safari, Notes, and Mail, and any Mac OS application in general. They aren't arbitrary, they're the emacs hotkeys, and work on many applications, not just ones on Mac OS.
| Shortcut | Function |
|---|
| ⌃ A | Move to the beginning of the line |
| ⌃ E | Move to the end of the line |
| ⌃ H | Delete the character left of the the cursor |
| ⌃ D | Delete the character right of the cursor |
| ⌃ U | Delete all text left of the cursor |
| ⌃ K | Delete all text right of the cursor |
| ⌃ O | Add a newline without moving the cursor |
| ⌃ T | Swap the characters left and right of the cursor |
Cursor Movement
If you're ever stuck without arrow keys (it could happen!) you can take advantage of these 4 shortcuts.
| Shortcut | Function |
|---|
| ⌃ F | Move cursor → |
| ⌃ B | Move cursor ← |
| ⌃ P | Move cursor ↑ |
| ⌃ N | Move cursor ↓ |
Universal Shortcuts
| Shortcut | Function |
|---|
| ⌘ , | Open preferences window |
| ⌘ ⇧ / | Open help menu for current app |
| ⌘ ⌃ F | Open app in full-screen |
| ⌥ ⌘ I | Open inspect element |
Navigating Folders
| Shortcut | Function |
|---|
| ⌘ ↑ | Open the parent folder |
| ⌘ ↓ | Open the file/folder |
| ⌘ → | Open the folder (list view) |
| ⌘ ← | Close the folder (list view) |
Opening Folders
| Shortcut | Function |
|---|
| ⌘ ⇧ G | Go to folder |
| ⌘ ⇧ D | Open the Desktop folder |
| ⌘ ⇧ O | Open the Documents folder |
| ⌥ ⌘ L | Open the Downloads folder |
| ⌘ ⇧ H | Open the Home folder |
| ⌘ ⇧ A | Open the Applications folder |
| ⌘ ⇧ R | Open the AirDrop folder |
| ⌘ ⇧ I | Open the iCloud folder |
Adjusting the Finder Window
| Shortcut | Function |
|---|
| ⌘ ⌥ P | Show/hide the path bar |
| ⌘ ⌥ S | Show/hide the side bar |
| ⌘ ⌥ T | Show/hide the toolbar |
| ⌘ ⇧ T | Show/hide the tab bar |
| ⌘ / | Show/hide the status bar |
| ⌘ ⇧ P | Show/hide preview of selected file |
| ⌘ 1 | View folder's items as icons |
| ⌘ 2 | View folder's items as list |
| ⌘ 3 | View folder's items as columns |
| ⌥ ⌘ ⌃ 1 | Sort files by name |
| ⌥ ⌘ ⌃ 2 | Sort files by type |
| ⌥ ⌘ ⌃ 4 | Sort by date added |
| ⌥ ⌘ ⌃ 5 | Sort by date modified |
Safari
| Shortcut | Function |
|---|
| ⌘ ⇧ \ | Show all tabs |
| ⌘ L | Select the current page's URL |
| ⌘ ⇧ R | Open in reader-view |
| ⌘ ⇧ I | Mail link of current page |
| ⌘ D | Add current page to bookmarks |
| ⌘ ⇧ D | Add current page to reading list |
| ⌥ ⌘ L | Open the downloads folder |
| ⌥ ⌘ E | Reset the cache |
| ⌘ ⇧ C | Start/stop select element |
| ⌥ ⌘ C | Open JavaScript Console |
| ⌥ ⌘ I | Open/close inspect element (also closes JavaScript console) |
| ⌥ ⌘ R | Hard refresh page |
Mail
| Shortcut | Function |
|---|
| ⌘ ⇧ N | Get new messages |
| ⌘ N | Write new message |
| ⌥ ⌘ F | Search mail for message |
| ⌘ ⇧ D | Send message |
| ⌥ ⌘ J | Empty junk mailbox |
| ⌘ ⇧ ⌫ | Empty trash mailbox |
Calculator
Documentation: [Calculator User Guide][]
[Calculator User Guide]: https://support.apple.com/guide/calculator/welcome/mac
| Shortcut | Function |
|---|
| ⌥ - | Negate the displayed value |
| ^ | Raise the displayed value to the power of the next value |
| e | Calculate the natural logarithm of the displayed value |
| ! | Calculate the factorial of the displayed value |
Screenshots
Screenshot directly from terminal
There's a hidden terminal command screencapture that you can use to capture a screenshot of your current window.
Capture the screen, save to example.png
screencapture 'example.png'
Capture the screen, save to the clipboard
Capture the screen, disable the "click" sound effect
screencapture -x 'example.png'
Capture the screen, (but after 10 second delay)
screencapture -T 10 'example.png' &
Start screen recording from the terminal
You can even use screencapture to record video. The -V flag specifies to capture a video and the -A flag specifies to capture audio as well.
Change default screenshot location
I like to put my screenshots in the ~/Downloads directory. Luckily there's a terminal command for that.
Change default screenshot filetype
By default, screenshots save as PNG files, but you can change this
Audio
Custom Sound Effects
The default system alert sounds are located in /System/Library/Sounds, and you
can place your own custom alert sounds in the ~/Library/Sounds directory. Your
custom alert sound must be an AIFF file (e.g. example.aiff).
If you'd like to discover sounds on your computer, use a recursive glob
to discover audio files within the system library
print -l /System/Library/**/*.aiff
For instance, to play a sound, use the afplay command, and provide it the sound file
you'd like to play. For example, the command below plays the default alert sound on macOS
afplay '/System/Library/Sounds/Tink.aiff'
Move cursor with the mouse in terminal
This is a cool trick I just discovered. Start typing out a command on the terminal, and then hold ⌥
Now try clicking on a different part of the command you're entering. It will move the cursor to that location!
Update Software in the Terminal
You can actually update the software on your computer directly from the terminal.
Fonts
The default terminal font, SF Mono, is by default hidden from the Font Book, and is available exclusively for use in the terminal app. To copy SF Mono to your computer's Font Book, run this command.
cp -R /System/Applications/Utilities/Terminal.app/Contents/Resources/Fonts/* /Library/Fonts
Disable User Photo
Setting Keyboard Shortcuts from Terminal
Store your keyboard shortcuts in the directory ~/Library/KeyBindings/DefaultKeyBinding.dict. Note that you have to first create ~/Library/KeyBindings since it won't exist at first.
@ : ⌘
^ : ⌃
~ : ⌥
$ : ⇧
← : \U2190
↑ : \U2191
→ : \U2192
↓ : \U2193
Fix Permissions
If you mess up your /etc files, like I did when I accidentally made every file executable, you can run this command to reset all of the permissions.
If you mess up your /etc/sudoers file, you'll have to boot into single-user mode with ⌘ S during power on. From there, you can enter the following commands.
Reset sudoers file
mount -uw /
chown root:wheel /etc/sudoers
chmod 440 /etc/sudoers
reboot
reboot
Customize Launch Application for File Extension
The property list file that controls which app launches for a particular filetype is located deep in Launch Services.
Default Application
You can install the command duti on homebrew to configure the default application that opens when you click on a file with a particular file extension. I've included an example below:
Convert SVG to PNG
Install librsvg, which is built by GNOME
If you want to convert example.svg into a 1024x1024 PNG file, you have a few
choices. These are ordered from best to worst.
avconvert
I'm going to write some notes about conversions between audio and video file
formats here. Some useful commands will appear below, but first I want to give a
breakdown of the ecosystem around audio, video, and image file formats.
First, the Moving Picture Experts Group (MPEG) is a group formed by ISO and IEC
to standardize the way audio and visual data is compressed and transmitted
across the internet. MPEG-4 is a method of defining compression of audio and
visual (AV) digital data. It was introduced in late 1998 and designated a
standard for a group of audio and video coding formats and related technology
agreed upon by the ISO/IEC Moving Picture Experts Group (MPEG). It was
introduced in late 1998 and designated a standard for a group of audio and video
coding formats and related technology agreed upon by the ISO/IEC Moving Picture
Experts Group (MPEG)
Encode MOV file video.mov as an H.265 (HEVC) encoded M4V file video.m4v preserving the original video resolution
avconvert -p 'PresetHEVCHighestQuality' -s 'video.mov' -o 'video.mp4'
Encode MOV file video.mov as an H.265 (HEVC) encoded M4V file with 1080p resolution
# You can add the '-q' flag to suppress output
avconvert -p 'PresetHEVC1920x1080' -s 'video.mov' -o 'video@1080p.m4v'
Encode MOV file video.mov as an H.264 encoded MOV file with 720p resolution
avconvert -p 'Preset640x480' -s 'video.mov' -o 'video@720p.mov'
Encode MOV file video.mov as an H.264 encoded MOV file with 420p resolution
```shell
avconvert -p 'Preset640x480' -s 'video.mov' -o 'video@420p.mov'
```
Convert MP3 to M4A
networksetup
The networksetup command allows you to configure your System Preference's Network settings directly from your terminal.
Get the current DNS servers
networksetup \
-getdnsservers 'Wi-Fi'
Configure the DNS servers
Using Google's DNS:
networksetup \
-setdnsservers 'Wi-Fi' \
'8.8.8.8' \
'8.8.4.4' \
'2001:4860:4860::8888' \
'2001:4860:4860::8844'
Using CloudFlare's DNS:
networksetup \
-setdnsservers 'Wi-Fi' \
'1.1.1.1' \
'1.0.0.1' \
'2606:4700:4700::1111' \
'2606:4700:4700::1001'
Get the local machine's MAC address
Configure the SOCKS proxy
ssh -fNCD 3339 bastion@remote.site
networksetup -setsocksfirewallproxy Wi-Fi 127.0.0.1 3339
networksetup -setsocksfirewallproxy Wi-Fi 127.0.0.1 3339
Enable the SOCKS proxy
networksetup -setsocksfirewallproxystate Wi-Fi on
Disable the SOCKS proxy
networksetup -setsocksfirewallproxystate Wi-Fi off
List preferred wireless networks
networksetup -listpreferredwirelessnetworks en0
Remove a preferred wireless network
networksetup -removepreferredwirelessnetwork en0 <network>
Connect to a WiFi Network
networksetup -setairportnetwork en0 <WiFi name> <password>
List order of network devices used to connect to the internet
networksetup -listnetworkserviceorder
Check if Wi-Fi is currently enabled
networksetup -getnetworkserviceenabled Wi-Fi
Get the name of the current network an interface is connected to
networksetup -getairportnetwork en0
Print detailed information about the current network connection
networksetup -getinfo Wi-Fi
# dhcp configuration
# IP address: 10.26.206.163
# Subnet mask: 255.255.0.0
# Router: 10.26.0.1
# Client ID:
# IPv6: Automatic
# IPv6 IP address: none
# IPv6 Router: none
# Wi-Fi ID: 6c:96:cf:dc:e5:cb
# Wi-Fi ID: 6c:96:cf:dc:e5:cb
airport
There is a hidden command, called airport. To use it, add the directory containing this command to your path upon initializing a new shell, by adding the following to your configuration file .zshrc:
path+=(/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport(N))
Programmatically add the airport command to the ${PATH}
file=/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport
>> ~/.zshrc < =(<<<"path+=(${file})")
Scan available WiFi networks
Disconnect from the current WiFi network
scutil
tmutil
If you have a Time Capsule, you can use the tmutil utility to interface with Time Machine from your terminal.
Backups are stored in the following location:
/Volumes/Time Machine Backups/Backups.backupdb/My Macbook Pro/2019-08-07-061700
/Volumes/Time Machine Backups/Backups.backupdb/My Macbook Pro/2019-08-07-061700
Speeding Up Time Machine Backups
If you are having trouble because time machine is taking too long, there's a way to speed up the pace of the back-up.
The changes made in this command are temporary, they will automatically reset to their default state on their own once the computer has been rebooted.
Saving Local Snapshots
By default, Time Machine will create local snapshots, locally stored backup volumes when it can't connect to your Time Capsule.
Enable Local Snapshots
Disable Local Snapshots
Excluding Certain Files & Folders
By default, Time Machine will back up everything on your drive. You may, however, have data from large directories stored elsewhere. If so, it might be a good idea to exclude that directory from Time Machine's backups, in the interest of saving space.
You can also check if a given file, directory, or volume is excluded
Check if a file is excluded
tmutil isexcluded ~/Downloads
# => [Included] /Users/austin/Downloads
# => [Included] /Users/austin/Downloads
See an exhaustive list of what's being ignored
sudo mdfind "com_apple_backup_excludeItem = 'com.apple.backupd'"
Restore files to their previous state
It's pretty hard to reliably exclude things using the native CLI tools. I've heard that asimov is a great tool to reduce the size of time machine backups.
Create User from Command Line
Adding a new user to a Mac computer from a Terminal window requires you to define the user’s name, set a password, create the user’s home directory and configure their system permissions.
Create a user named tommy
dscl . create /Users/tommy
Set tommy's shell to /bin/zsh
dscl . create '/Users/tommy' UserShell '/bin/zsh'
Set Tommy's have the home directory /Users/tommy
dscl . create '/Users/tommy' NFSHomeDirectory '/Users/tommy'
createhomedir -u tommy -c
Set tommy's RealName to Tommy Trojan
dscl . create '/Users/tommy' RealName 'Tommy Trojan'
Give tommy a UID number, (for instance, 502)
dscl . create '/Users/tommy' UniqueID 502
Give tommy the primary group ID of 20 (the default for the staff group on macOS)
dscl . create '/Users/username' PrimaryGroupID 20
Give tommy the password fighton
dscl . passwd /Users/tommy 'fighton'
Add tommy to the list of user's that can be logged into with ssh
dseditgroup -o edit -t user -a tommy com.apple.access_ssh
Optionally add tommy to the list of admin users on the computer
dseditgroup -o edit -d tommy -t user admin
Hidden Users
Allow the creation of secret users, hidden if their UID is 500 or lower
sudo defaults write /Library/Preferences/com.apple.loginwindow Hide500Users -bool YES
Make the user tommy a hidden user
# Enabling hidden status
sudo dscl . create '/Users/tommy' IsHidden 1
# Disabling hidden status
sudo dscl . create '/Users/tommy' IsHidden 0
Disable the Other... user from appearing in the login screen
sudo defaults write /Library/Preferences/com.apple.loginwindow SHOWOTHERUSERS_MANAGED -bool false
Add tommy to the list of users hidden on the login screen
sudo defaults write /Library/Preferences/com.apple.loginwindow HiddenUsersList -array-add "tommy"
Hide the public share folder for the user whose long name is Tommy Trojan
sudo dscl . delete "/SharePoints/Hidden Tommy Trojan's Public Folder"
Force the user tommy to set a new password
sudo dscl . passwd '/Users/tommy' ''
sudo pwpolicy -u username -setpolicy 'newPasswordRequired=1'
sudo rm -r ~tommy/Library/Keychains/*
sudo rm -r ~tommy/Library/Keychains/*
Get a list of all users short names
Get detailed info on a particular user
sudo dscl . read /Users/<username>
Get a specific value from a user
dscl . read /Users/<username> <key>
Get detailed info on all users
Get a specific value from all users
dscl . readall /Users <key>
Get concise information about all users
Get all of the groups that user root is associated with
dscl . search /Groups GroupMembership 'root'
Get the name os all of the groups
Check if the user tommy is a member of the group admin
dseditgroup -o checkmember -m 'tommy' 'admin'
Add the user tommy to the group admin
dseditgroup -o edit -a 'tommy' -t user 'admin'
Change a user's information
# [ macOS ]
sudo dscl . change /Users/austin RealName 'Austin Traver' 'Fake Name'
# confirming the change
finger austin
# reverting the chang
sudo dscl . -change /Users/austin RealName 'Fake Name' 'Austin Traver'
sudo dscl . -change /Users/austin RealName 'Fake Name' 'Austin Traver'
sysadminctl
fdesetup
Single User Mode
Power Sound
System Integrity Protection
If you need to make changes to the file system, it might require disabling system integrity protection. By default, the following directories are protected:
/System/usr/bin/sbin/var
There are three directories that are not protected:
/Applications/Library/usr/local
Disabling system integrity protection
Enabling system integrity protection
Checking system integrity protection
Configuring the Login Page
Show additional info by clicking the clock in the top-right corner
sudo defaults write /Library/Preferences/com.apple.loginwindow AdminHostInfo IPAddress
Adding a welcome message to the login page
# [ Adding the message ]
sudo defaults write /Library/Preferences/com.apple.loginwindow LoginwindowText -string 'Welcome back'
# [ Removing the message ]
sudo defaults delete /Library/Preferences/com.apple.loginwindow LoginwindowText
Adding a script to run at login
sudo defaults write com.apple.loginwindow LoginHook /path/to/script
Adding a graphic+text banner to appear upon login
sudo cp ./banner /Library/Security/PolicyBanner
Disable buttons on the login page
sudo defaults write /Library/Preferences/com.apple.loginwindow ShutDownDisabled -bool true
sudo defaults write /Library/Preferences/com.apple.loginwindow RestartDisabled -bool true
sudo defaults write /Library/Preferences/com.apple.loginwindow SleepDisabled -bool true
sudo defaults write /Library/Preferences/com.apple.loginwindow SleepDisabled -bool true
Reenable buttons on the login page
sudo defaults write /Library/Preferences/com.apple.loginwindow ShutDownDisabled -bool false
sudo defaults write /Library/Preferences/com.apple.loginwindow RestartDisabled -bool false
sudo defaults write /Library/Preferences/com.apple.loginwindow SleepDisabled -bool false
sudo defaults write /Library/Preferences/com.apple.loginwindow SleepDisabled -bool false
Disable the user icons from the login page (this sets the "username & password" format as the default for the login page)
sudo defaults write /Library/Preferences/com.apple.loginwindow SHOWFULLNAME -bool true
diskutil
Something learned from man hdiutil:
/dev/rdisk nodes are character-special devices, but are "raw" in the BSD sense and force block-aligned I/O. They are closer to the physical disk than the buffer cache. /dev/disk nodes, on the other hand, are buffered block-special devices and are used primarily by the kernel's filesystem code. In layman's terms /dev/rdisk goes almost directly to disk and /dev/disk goes via a longer more expensive route
View available storage devices
Erase a hard drive's partitions
sudo diskutil partitionDisk /dev/disk2 1 MBR "Free Space" "%noformat%" 100%
Copy image to a new hard drive
diskutil unmount /dev/disk2s1
sudo dd bs=1M if='/path/to/file.img' of='/dev/rdisk2' conv=sync
sudo dd bs=1M if='/path/to/file.img' of='/dev/rdisk2' conv=sync
Copy the current hard drive into an image
# Exporting an SD card save
sudo dd bs=4M if=/dev/sdb of=raspbian.img
# Importing an SD card save
sudo dd bs=4M if=raspbian.img of=/dev/sdb
Eject a device
sudo diskutil eject /dev/rdisk2
Enable vpn connection on port 3340
kill $(lsof -ti :3340) &> /dev/null
ssh -fNCD 3340 'ssh://bastion@52.52.124.230:22'
networksetup -setsocksfirewallproxystate Wi-Fi on
return 0
return 0
Disable vpn connection on port 3340
kill $(lsof -ti :3340) &> /dev/null
networksetup -setsocksfirewallproxystate Wi-Fi off
return 0
macOS Books
New to macOS Catalina is the Books application, which provides a cleaner interface for handling audiobooks on your Mac.
macOS Notes
- Notes are stored in a sqlite database, located on your computer at
~/Library/Containers/com.apple.Notes/Data/Library/Notes/
Printing
Scan for printers on the network that support the IPP protocol
Scan for hosts on the network that have enabled login via the SSH protocol.
Ping the printer to see if it responds
ping BRN3C2AF4C9463F.local
Setup the printer, giving it the name Brother
# `-p 'Brother'`: Name the printer "Brother"
# `-E`: Use TLS encryption when communicating across the network
# `-v 'ipp://brother.local'`: Print to the URI `<ipp://brother.local>`
# `-m 'everywhere'`: Use the IPP protocol
lpadmin -p 'Brother' -E -v 'ipp://brother.local' -m 'everywhere'
Make this printer the default
lpoptions -E -d 'Brother' -o sides=two-sided-long-edge
# Creates ~/.cups/lpoptions with one line: "Default Brother sides=two-sided-long-edge"
-p 'Brother': Name the printer "Brother"-E: Use TLS encryption when communicating across the network-d: Make this the default printer-o: Set the option sides to two-sided-long-edge
Print a file
Check the current printer configurations
Virtual Network Computing VNC
Virtual Network Computing, or VNC, is more commonly known as Screen Sharing, as this is the name of the application used for VNC on macOS. Your computer listens for VNC connections on port 5900, and you can use the <vnc://user@host.net> syntax to reach a particular user at a particular address.
Launching a Screen Share from the terminal:
open vnc://tommy@trojan.net
Enabling Screen Sharing from the terminal:
sudo defaults write /var/db/launchd.db/com.apple.launchd/overrides.plist com.apple.screensharing -dict Disabled -bool false
Disabling Screen Sharing from the terminal:
sudo defaults write /var/db/launchd.db/com.apple.launchd/overrides.plist com.apple.screensharing -dict Disabled -bool true
Icons
You can find icons in some of the following locations:
/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/
You can also find some of the iOS icons in the following places
/System/Library/Extensions/IOSCSIArchitectureModelFamily.kext/Contents/Resources/
/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/
Listing all icon files
print -l /System/Library/**/*/Contents/Resources/*.icns
I've made a script that can convert an image into an icon
Filetype Conversion for Printing
Defaults
defaults is a powerful command. defaults a tool to utilize when exporting and importing settings across machines
You can prohibit the modification of Finder preferences by selecting Preferences... in the menu bar. As to why you'd want to do this, I have no idea, but here you go:
Similarly, you could prohibit the Go to folder action in Finder as well, for whatever reason
If you're tired of .DS_Store files popping up in all of your directories, there's a command to disable them entirely. Before you do however, it's worth nothing that the .DS_Store file is one that contains useful metadata about your file system browsing preferences, such as "Whether to open a folder in 'Application View' or in 'List View'"
Disable creation of .DS_Store files
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true
Delete dock hiding delay
defaults write com.apple.dock autohide-delay -float 0
killall Dock
killall Dock
Change minimum file size threshold for Mail Drop for macOS Mail
# 1024 = 1MB
defaults write com.apple.mail minSizeKB 1024
defaults write com.apple.mail minSizeKB 1024
Hide the preview of images attached to a message in Mail
defaults write com.apple.mail DisableInlineAttachmentViewing -bool true
TextEdit
Misc
Reset the DNS cache
sudo discoveryutil udnsflushcaches
Change the cursor's blink rate
# Enter time in milliseconds
defaults write -g NSTextInsertionPointBlinkPeriodOn -float 200
Remove the animation when resizing windows
# Disable slow animation
defaults write -g NSWindowResizeTime -float 0.001
Remove the animation when opening a new window
# Disable slow animation
defaults write -g NSAutomaticWindowAnimationsEnabled -bool false; killall Finder SystemUIServer
Remove the animation when focusing on a field
Source: https://osxdaily.com/2016/08/17/disable-focus-ring-animation-mac-os/
defaults write -g NSUseAnimatedFocusRing -bool false; killall Finder SystemUIServer
Disable filenames from including date on screenshots
defaults write com.apple.screencapture 'include-date' -bool false
killall SystemUIServer
Disable power button sleeping the system
defaults write com.apple.loginwindow PowerButtonSleepsSystem -bool false
Treat the help window (the one that shows user manuals) as a normal window link to source
defaults write com.apple.helpviewer DevMode -bool true
Change the format of the clock in the menu bar (A great tutorial on
setting the date and time format)
defaults write com.apple.menuextra.clock DateFormat 'EEE dd MMM h:mm:ss a'
QuickLook
Extending QuickLook Previews
Spotlight Search
Boolean Operators
Search Operators
author:
date:
Today
Yesterday
Before January 1st, 2020
After January 1st, 2020
created:
modified:
weather:
bitrate:
iso:
wiki:
Searching for messages in Mail
Spotlight by default searches through mail as well, so to find a message, you can retrieve it from Spotlight, without even opening the Mail application.
To learn more about searching the Mail app
The Apple support article that covers how to search for emails in Mail on Mac is not sufficiently comprehensive in my opinion, so I've added more concrete instances of valid search operators in the examples found below.
Search for all mail sent to: "Tommy Trojan"
to:"Tommy Trojan"
to:ttrojan@usc.edu
Search for all mail received from "Billy Bruin"
from:"Billy Bruin"
from:bbruin@ucla.edu
Search for all mail with subject: "Secret Recipe"
Search for all mail whose subject contains both secret and recipe
subject:secret subject:recipe
Search for all mail from 2018 and earlier
- With calendar format set to
ISO 8601
Search for mail between 2017 and 2019 (note the range is not inclusive)
Type to:recipient@example.com to find all sent mail addressed to a specific recipient at a specific domain.
The subject search operator limits the search results to the contents of email subject lines.
Type subject:cookie in the search field to return all emails with the word "cookie" in the subject line.
Type subject:"cookie recipe" to find all mail with the phrase "cookie recipe" in the subject line.
Type subject:cookie subject:recipe to find all mail with both "cookie" and "recipe" in any order in the subject line.
Spotlight Siri Knowledge
Siri uses natural language processing (NLP) to identify good matches for searches that don't use search operators. Some useful examples are included below:
Get the score of the Sharks vs Ducks game
sharks vs ducks
sharks game
sharks game
View the wikipedia entries matched by Grease
View the score of the Yankees game
View the schedule of the Yankees
View the schedule of the Giants (Football) team
View the conversion rate of USD to RMB
Convert temperature from 58 degrees Fahrenheit to Celsius
Convert temperature from 58 degrees Fahrenheit to Kelvin
View the stock price for symbol V
Disable Spotlight Index of Network Drives
Have Spotlight ignore every external volume
sudo defaults write /Library/Preferences/com.apple.SpotlightServer.plist ExternalVolumesIgnore -bool True
Have Spotlight ignore, by default, each new network volume it encounters, from here on out:
sudo defaults write /Library/Preferences/com.apple.SpotlightServer.plist ExternalVolumesDefaultOff -bool True
Safari Web Extensions
To convert Firefox web extensions into Safari web extensions, you'll need Xcode
12, and the command-line tools that accompany it
CalDAV Synchronization
You can control which calendars in your Google Calendar to share with iCloud by going to Google Calendar's page about sync settings
URL Schemes
Compressor
The Compressor application is part of the iWork premium set of apps, which includes applications like "Logic Pro" and "Final Cut Pro".
Other Useful Commands
Check the battery life from your terminal
Disable sleep for one session
Disable sleep entirely
sudo systemsetup -setcomputersleep Never
Immediately put the computer to sleep
Schedule for the computer to regularly wake up (or boot) on weekdays @ 7:45AM
pmset repeat wakeorpoweron MTWRF 07:45:00
Schedule for the computer to sleep on 12/24 @ 8:00AM
pmset schedule sleep "12/24/2019 08:00:00"
Schedule for computer to sleep in 1 hour:
sudo systemsetup -setcomputersleep 60
Check when the computer is scheduled to sleep
sudo systemsetup -getcomputersleep
Schedule for the computer to wake on 12/24 @ 8:00PM
pmset schedule wake "12/24/2019 20:00:00"
Restart the computer immediately
# Option 1
sudo reboot now
# Option 2
sudo shutdown -r now
Shut down the computer immediately
Dangerously shut the computer down immediately
AppleScript
You can trigger AppleScript from a web link using the applescript URL scheme.
For instance, this is the AppleScript to print hello world on a user's computer.
applescript://com.apple.scripteditor?action=new&script=display%20dialog%20%22hello%20world%22
Color Swatches
Screen Capture
I recommend reading Apple's article Take a screenshot on your Mac. I learned something I didn't know. You can hold the ⌥ modifier key while taking a screenshot of a window to prevent the drop shadow from appearing!
Personally, I think the drop shadow is a good touch. If, however, you prefer that drop shadows be disabled by default when taking a screen capture of an application window, you can use the following command.
FaceTime
When you're on a FaceTime audio call, or any phone call for that matter, your desktop will be presented with a small window in the top-right corner. That window can be bothersome, as it floats on top of of whatever applications you're using. I discovered how it can be hidden:
Hide the FaceTime window
pkill -9 FaceTimeNotificationService
AirDrop
You can add AirDrop to the dock by visiting the following directory.
/System/Library/CoreServices/Finder.app/Contents/Applications
From there, click and drag the AirDrop.app icon to your dock
You can also drag the iCloud.app icon to your dock as well.
Launchpad
You can change the Launchpad icon grid layout, but it requires some defaults write commands, provided below.
Set the number of rows in Launchpad
# Default: 5 rows
defaults write com.apple.dock springboard-rows -int 5
killall Dock
Set the number of columns in Launchpad
# Default 7 columns
defaults write com.apple.dock springboard-columns -int 7
killall Dock
Restore the default Launchpad app layout
defaults write com.apple.dock ResetLaunchPad -bool true
killall Dock
Restore the Launchpad dimensions to its original 5x7 layout
defaults delete com.apple.dock springboard-rows
defaults delete com.apple.dock springboard-columns
killall Dock
Feedback Assistant
The Feedback app is available on all iOS devices, even if they aren't running a beta. devices.
To get to it, open up Safari and navigate to the URL applefeedback://
xattr
xcode-select
sips
Mac has an inbuild tool for editing images called sips, which is an
abbreviation for scriptable image processing system. You can learn about it
here, but I encourage you to check out man sips and sips --help as well.
Convert PNG file to JPEG format
# Valid formats are as follows:
# jpeg | tiff | png | gif | jp2 |
# pict | bmp | qtif | psd | sgi | tga
sips -s format jpeg './image.png' -o './image.jpeg'
Rotate PNG file 90 degrees
Flip an image horizontally
sips -f horizontal 'image.png'
Flip an image vertically
sips -f vertical 'image.png'
Crop an image to HEIGHT by WIDTH
sips -c HEIGHT WIDTH 'image.png'
Resize image to updated dimensions HEIGHT by WIDTH.
(Note: this may alter the actual aspect ratio)
sips -z HEIGHT WIDTH 'image.png'
Resize image to a maximum height or width DIMENSION,
preserving the existing aspect ratio
sips -Z DIMENSION 'image.png'
Get the dimensions (width and height) of an image
sips -g pixelWidth -g pixelHeight IMAGE
Daemons, Agents, and Automation
daemon
: A computer program that runs as a background process.
agent
: A program that acts on behalf of another program, or on behalf of another
user.
user agent
: a daemon specific to a logged-in user that only executes while that user
is logged in.
process identifier
: a number used by most operating system kernels to
uniquely identify an active process.
The original daemon is init, which has process identifier #1 because it is the first process
started during the booting of the computer system.
macOS has a more robust alternative to cron which allows daemon processes to
be triggered on a systematic fashion. Using the launchctl (launch control)
command, you can create daemon processes that will automatically run by the
system.
These files take the form of plist files and are found in several system
directories:
- /Library/LaunchAgents
- /Library/LaunchDaemons
- /System/Library/LaunchAgents
- /System/Library/LaunchDaemons
- ${HOME}/Library/LaunchAgents
If you write or install personal plist files, they will ideally go in the home
directory. A good example file to begin understanding the syntax can be located
in /System/Library/LaunchDaemons/ssh.plist, which is the file used to launch
the ssh daemon server that listens for incoming ssh connections.
Specifying privacy-sensitive files and folders in a launchd property list might
not work as expected and prevent the service from running. Having Program or
Program Arguments pointing to an executable in a privacy sensitive location is
currently allowed, but may be restricted in a future release.
To comply with the new privacy protections, resources for a launchd service must
be stored in locations that aren't privacy sensitive. If necessary, the app can
set up resources during its execution rather than using launchd property list
keys, making it possible to grant the app access using System Preferences >
Security & Privacy > Privacy. The following launchd property list keys are
affected: Keep Alive, Path State, Queue Directories, Sockets, Sock Path Name, Standard Error``Path, Standard In Path, Standard Out Path, and
Watch Paths.
If you're setting up processes in /Library/LaunchDaemons, which are run as the
root user, then make sure to set the file permissions appropriately using
chown root:wheel <file> and chmod 644 <file>
View launchctl information about a daemon process by its PID:
sudo launchctl profinfo <PID>
View information about all services pertaining to a user's UID:
launchctl print user/$UID
View information about a particular running service under a user's UID:
# ~/Library/LaunchAgents/com.tommy.foo.plist
launchctl print com.tommy.foo
For all daemon processes owned by the current user, print true if they are disabled
launchctl print-disabled user/$UID
launchctl has changed for the better in 10.11.4
Type the command without arguments to get the help. You'll see new domains to search and new commands.
For your processes: if it's not in the system domain it's probably in the domain of that particular user.
However, since you'll be logged into the GUI, you might want to check the domain of the GUI, which is kept separate.
Checking the domain of the GUI
launchctl print gui/<uid>
launchctl print gui/<uid>/com.example.service
GUI domains are for processes that apply to a user interface.
User domains are for processes that invoke daemons that only apply to a particular logged-in user.
System domains are for system daemon processes, and apply to all users within that system.
To learn more, read man launchctl or read Apple's article about Creating Launch Daemons and Agents
I wasn't sure where the best place to put this is, but it will
link the latest version of GCC installed by Homebrew into /usr/local/bin,
while also removing the version number suffixed to the filename by Homebrew's
installation formula.
# Choose the directory containing the latest version of GCC
# as indicated by the highest number suffixed to
# the filepath of the package directory
print -v version /usr/local/opt/gcc@<->(n[-1])
version=${version#*@}
for file in /usr/local/opt/gcc@${version}/bin/*-${version}(*); do
tail=${file:t}
ln -sf ${file} /usr/local/bin/${tail%-*}
done
If symbolic links are overkill for you, then check this out.
The snippet below will hash the executable corresponding with each file,
which zsh will expand each command to when called, and will do this up
until the next point that the path is modified by the shell. At that point,
these hashed commands will be rehashed, meaning the location specified in the
hash command's specified directory will have its executable overwritten
and replaced by the executable in the foremost directory in the path
containing an executable with a matching name.
print -v version /usr/local/opt/gcc@<->(n[-1])
version=${version#*@}
for file in /usr/local/opt/gcc@${version}/bin/*-${version}(*); {
tail=${file:t}
hash ${tail%-*}=${file}
}
iMessage
This isn't written down anywhere, so I'm writing it here: You can
send message effects on the macOS Messages application with
a keyboard shortcut: ⌘ ⇧ A
You can also replace the drafted message with previous messages. Use ⌥ ↑ and ⌥ ↓ to navigate through the message history.
Using coreutils on macOS
Hiding Files
Make a file or folder invisible in Mac OS X Finder. You’ll need to open Terminal to get started, then just use the following syntax:
setfile -a V testfile.txt
Poof! Like magic, the file or folder is no longer visible via the Finder GUI, but don’t worry your files are still there and you can find them via the command line and will show with an ls command. If you want to make your files and folders visible again, use this command:
Now the file/folder will be visible again to the Finder, cool huh?
Custom Password Policy
You can delete the macOS password policy restrictions using the following command:
pwpolicy -clearaccountpolicies
Getting IPv6 Address
TIL! If you hold ⌥ in macOS (⇧ on Windows) when left-clicking a scroll bar, you will jump to that position in the document.