Mac OS
The best OS a parent's money can buy
- Steve Jobs, probably
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 |
Sleep, Restart, Shut Down, Log Out
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 ↓ |
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 |
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 |
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
screencapture -c
-
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.
-
Record the screen for 10 seconds
screencapture -V 10 'example.mp4' &
Change default screenshot location
I like to put my screenshots in the ~/Downloads
directory. Luckily there's a terminal command for that.
-
Set the directory of all future screenshots.
defaults write com.apple.screencapture location ~/Downloads && killall SystemUIServer
Change default screenshot filetype
By default, screenshots save as PNG files, but you can change this
-
Change default screenshot filetype from PNG to JPG
defaults write com.apple.screencapture type -string 'jpg' && killall SystemUIServer
-
Change the screen capture filename to
screenshot
defaults write com.apple.screencapture name -string 'screenshot' && killall SystemUIServer
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
).
-
Use ffmpeg to convert an
.mp3
to.aiff
ffmpeg -i './input.mp3' "${HOME}/Library/Sounds/custom.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.
-
List available software updates
softwareupdate -l
-
The
-l
flag is the list option -
Install all updates
# Short form sudo softwareupdate -iaR # Long form sudo softwareupdate --install --all --restart
- The
-i
flag is the install option - The
-a
flag is the all option - The
-r
flag is the restart option, so the computer will restart and install the updates after they are downloaded
- The
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
-
Although the GUI doesn't give us an option to disable user-pictures, you can do it with the terminal commands below.
# Delete the image chosen during OS installation sudo dscl . delete /Users/${USER} Picture # Delete an image chosen by the user later on sudo dscl . delete /Users/${USER} JPEGPhoto
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.
-
Reset system file permissions to default
diskutil resetUserPermissions / $(id -u)
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.
-
Open the Launch Services properties list file
open file:///Users/${USER}/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist
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:
-
Setting default application used for
.c
files.# Set apple as the default editor for .c files duti -s com.apple.Xcode public.c editor # Check the current handlers performed by a UTI duti -l com.apple.Safari # Describe information about the default app for extension `mp4` duti -x mp4 duti -x mp4
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.
-
Using
librsvg
:# If necessary brew install librsvg rsvg-convert -w 4096 -h 4096 example.svg -o example.png
-
Using magick resize
# If necessary brew install imagemagick magick convert \ -resize '1024x1024' \ -background 'none' \ 'input.svg' 'output.png'
-
Using
qlmanage
, the built-in command-line utility for QuickLook:qlmanage -ts 1024 -o . example.svg
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 filevideo.m4v
preserving the original video resolutionavconvert -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 resolutionavconvert -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
-
Convert
song.mp3
into an AAC encoded M4A audio filesong.m4a
# -v is for "verbose" avconvert -v -p PresetAppleM4A -s ~/Desktop/song.mp3 -o ~/Desktop/song.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
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
networksetup -getmacaddress Wi-Fi | awk '{print $3}'
-
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.
-
Adding the
airport
command to the${PATH}
file=/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport >> ~/.zshrc < =(<<<"path+=(${file})")
-
Scan available WiFi networks
airport -s
-
Disconnect from the current WiFi network
airport -z
scutil
-
Get the computer's name
scutil --get ComputerName
-
Set the computer's name
scutil --set ComputerName "Tommy's MacBook Pro"
-
Get the host name
scutil --get HostName
-
Set the host name
scutil --set HostName "nova"
-
Get the localhost name (used for Bonjour)
scutil --get LocalHostName
-
Set the localhost name (used for Bonjour)
scutil --set LocalHostName "nova"
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:
tmutil latestbackup
/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
-
Turn on Time Machine
tmutil enable
-
Turn off Time Machine
tmutil disable
-
Start backing up to the Time Capsule
tmutil startbackup
-
Stop backing up to the Time Capsule
tmutil stopbackup
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.
-
Enabling speedy backups (by disabling priority filtering)
sudo sysctl debug.lowpri_throttle_enabled=0
-
Disabling speedy backups (by enabling priority filtering)
sudo sysctl debug.lowpri_throttle_enabled=1
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
tmutil disablelocal
-
Disable Local Snapshots
tmutil enablelocal
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.
-
Exclude files in the directory
~/Downloads
from backupstmutil addexclusion ~/Downloads
-
Exclude the directory path
~/Downloads
from backupstmutil addexclusion -p ~/Downloads
-
Re-enable backups for the directory (and path)
~/Downloads
tmutil removeexclusion ~/Downloads
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
tmutil restore
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 thestaff
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 ofadmin
users on the computerdseditgroup -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 screensudo defaults write /Library/Preferences/com.apple.loginwindow SHOWOTHERUSERS_MANAGED -bool false
-
Add
tommy
to the list of users hidden on the login screensudo 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 passwordsudo 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
sudo dscl . list /Users
-
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
dscl . readall /Users
-
Get a specific value from all users
dscl . readall /Users <key>
-
Get concise information about all users
dscl . ls /Users
-
Get all of the groups that user
root
is associated withdscl . search /Groups GroupMembership 'root'
-
Get the name os all of the groups
dscl . ls /Groups
-
Check if the user
tommy
is a member of the groupadmin
dseditgroup -o checkmember -m 'tommy' 'admin'
-
Add the user
tommy
to the groupadmin
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'
-
Remove
tommy
from the list of users who are members of theadmin
groupdseditgroup -o edit -d 'tommy' -t user 'admin'
sysadminctl
-
Create a user
guest
with limited permissionssysadminctl -addUser guest -fullName 'Tommy Trojan' -UID 404 -shell /bin/zsh -home /Users/guest
# Use the user 'billy' and his password 'gobruins' to escalate privileges sysadminctl -adminUser 'billy' -adminPassword 'gobruins' \ -addUser 'tommy' \ -password 'fighton' \ -fullName 'Tommy Trojan' \ -UID 502 \ -shell /bin/zsh \ -home /Users/tommy
# Create the home directory for 'tommy' sudo createhomedir -c
-
Add a user's password to those capable of unlocking the FileVault at boot
# Use the existing admin account 'billy' whose password is 'gobruins' # to allow the new admin account 'tommy' to login with the 'fighton' password sysadminctl -adminUser 'billy' -adminPassword 'gobruins' -secureTokenOn 'tommy' -password 'fighton'
fdesetup
-
Restart the computer, but bypass FileVault
sudo fdesetup authrestart
Single User Mode
-
Reboot the computer into single user mode
sudo launchctl reboot -s system
Power Sound
-
Play the audio file that stores the "device is charging" chime.
afplay /System/Library/CoreServices/PowerChime.app/Contents/Resources/connect_power.aif
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
csrutil disable
-
Enabling system integrity protection
csrutil enable
-
Checking system integrity protection
csrutil status
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
diskutil list
-
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.
-
The Books app stores audiobook files in
~/Library/Containers/com.apple.BKAgentService/Data/Documents/iBooks/Books/Audiobooks
-
Keep Books in a more convenient folder:
ln -s ~/Library/Containers/com.apple.BKAgentService/Data/Documents/iBooks/Books ~/Books
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
protocoldns-sd -Z _ipp._tcp .
-
Scan for hosts on the network that have enabled login via the
SSH
protocol.dns-sd -Z _ssh._tcp .
-
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 optionsides
totwo-sided-long-edge
-
Print a file
lp ~/path/to/file.pdf
-
Check the current printer configurations
lpstat -v
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
-
Convert PNG file
pic.png
into ICNS filepic.icns
iconset=${1%%.*}.iconset mkdir -v ${iconset} for ((s=16; s<=512; s*=2)); do sips -z ${s} ${s} ${1} -o ${iconset}/icon_${s}x${s}.png done for ((s=16; s<=256; s*=2)); do sips -z ${s} ${s} ${1} -o ${iconset}/icon_${s}x${s}@2x.png done cp ${1} ${iconset}/icon_512x512@2x.png iconutil -c icns ${iconset} rm -R ${iconset}
Filetype Conversion for Printing
-
Convert a text file to PostScript
cupsfilter -m 'application/postscript' file.txt > file.ps
-
Convert a text file to PDF
cupsfilter -m 'application/pdf' file.txt > file.pdf
Defaults
defaults
is a powerful command. defaults
a tool to utilize when exporting and importing settings across machines
-
Display file extensions
defaults write NSGlobalDomain AppleShowAllExtensions -bool true killall Finder
-
Prevent file icons from displaying on the Desktop
defaults write com.apple.finder CreateDesktop -bool FALSE killall Finder
-
Enable quit button for Finder application
defaults write com.apple.finder QuitMenuItem -bool true killall Finder
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:
-
Disabling key repeat
defaults write -g InitialKeyRepeat -int 10
-
Resetting key repeat to default settings
defaults write -g InitialKeyRepeat -int 15 # 225 ms defaults write -g KeyRepeat -int 2 # 30 ms
-
Disable modification of Finder preferences
defaults write com.apple.finder ProhibitFinderPreferences -bool true killall Finder
Similarly, you could prohibit the Go to folder
action in Finder as well, for whatever reason
-
Disable
Go to folder
action in the menu bar:defaults write com.apple.finder ProhibitGoToFolder -bool true killall Finder
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
filesdefaults 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
-
Use plain text as the default in TextEdit instead of rich text
defaults write com.apple.TextEdit RichText -int 0
Misc
-
Reset the DNS cache
sudo discoveryutil udnsflushcaches
-
Change the cursor's blink rate
# Enter time in milliseconds defaults write -g NSTextInsertionPointBlinkPeriodOn -float 200
-
Disable the full screen animation
# Disable slow animation defaults write -g NSWindowResizeTime -float 0.001
-
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
-
Adding previews for markdown files
brew cask install qlmarkdown xattr -cr ~/Library/QuickLook/QLMarkdown.qlgenerator qlmanage -r qlmanage -r cache killall Finder
-
Adding syntax highlighting to code previews
-
Download the latest release
https://github.com/sbarex/SourceCodeSyntaxHighlight/releases
-
Sign the application
xattr -r -d com.apple.quarantine /Applications/Syntax\ Highlight.app
-
Customize themes here
~/Library/Application\ Support/Syntax\ Highlight/Themes
-
Customize CSS here
~/Library/Application\ Support/Syntax\ Highlight/Styles/global.css
-
Spotlight Search
-
⌘ ↓ Move to next category in search results
-
⌘ ↑ Move to previous category in search results
Boolean Operators
AND
OR
NOT
Search Operators
-
Search for results containing
Forest
but notGump
kind:movie Forest -Gump
-
List of valid options for the
kind:
operatorkind:app kind:contact kind:folder kind:image kind:movie kind:music kind:audio kind:jpeg kind:pdf kind:text kind:pdf kind:preferences kind:bookmark kind:font kind:fonts kind:presentation kind:mail kind:markdown kind:chat kind:event kind:reminder kind:reminder
author:
-
Documents written by Valerie
author:Valerie
date:
-
Today
date:today
-
Yesterday
date:yesterday
-
Before
January 1st, 2020
date:<2020-01-01
-
After
January 1st, 2020
date:>2020-01-01
created:
-
Files created after
January 1st, 2019
created:>2019-01-01
modified:
-
Files modified on
March 1st, 2010
modified:2010-03-01
-
Files modified before
2018
modified:<2018
weather:
-
View the weather in
Cupertino
weather:cupertino
-
View the definition of
wizard
define:esoteric
bitrate:
-
View files with a 128kbps bitrate
bitrate:128
iso:
-
View pictures with an ISO speed higher than 400
iso:>400
wiki:
-
View the wikipedia entry for the topic
boolean
wiki:boolean
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"subject:"Secret Recipe"
-
Search for all mail whose subject contains both
secret
andrecipe
subject:secret subject:recipe
-
Search for all mail from
2018
and earlier- With calendar format set to
ISO 8601
date:2018-12-31
- With calendar format set to
-
Search for mail between
2017
and2019
(note the range is not inclusive)date:2017-2020
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
wiki Grease
-
View the score of the Yankees game
score Yankees
-
View the schedule of the Yankees
schedule Yankees
-
View the schedule of the Giants (Football) team
Giants football schedule
-
View the conversion rate of
USD to RMB
1 USD in RMB
-
Convert temperature from 58 degrees Fahrenheit to Celsius
58 F to C
-
Convert temperature from 58 degrees Fahrenheit to Kelvin
58 F to K
-
View the stock price for symbol
V
V stock
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
-
Converting the extension from a Firefox extension into a Safari extension
xcrun safari-web-extension-converter [options] ./path/to/extension
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
-
Print out all supported URL schemes
/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump | grep -B6 'bindings:.*:'
Compressor
The Compressor application is part of the iWork premium set of apps, which includes applications like "Logic Pro" and "Final Cut Pro".
-
Using Compressor from the command line
alias compressor='/Applications/Compressor.app/Contents/MacOS/Compressor'
Other Useful Commands
-
Check the battery life from your terminal
pmset -g batt
-
Disable sleep for one session
pmset noidle &!
-
Disable sleep entirely
sudo systemsetup -setcomputersleep Never
-
Immediately put the computer to sleep
pmset sleepnow
-
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
sudo shutdown now
-
Dangerously shut the computer down immediately
sudo halt
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
-
Create an alert window that shows a dialog and presents the user with two choices
osascript <<< 'display alert "Do you accept?" buttons {"Cancel", "Yes"}'
-
Display a notification
-
Simple message
osascript <<< "display notification \"${message}\""
-
Message with a title
title='Breaking news' message='You are a hacker' osascript <<< "display notification \"${message}\" with title \"${title}\""
-
Message with a title and a subtitle
title="Breaking news" subtitle="No seriously" message="You are my sunshine" osascript <<< "display notification \"${message}\" with title \"${title}\" subtitle \"${subtitle}\""
-
Message with a title and a sound
title="Quick question" message="Did you hear that?" osascript <<< "display notification \"${message}\" with title \"${title}\" sound name \"default\""
-
Color Swatches
-
Swatches have an extension of
.clr
and can be found in~/Library/Colors
ls ~/Library/Colors
Output
NSColorPanelSwatches.plist Custom.clr Custom.clr
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.
-
Disable drop shadow for application window screenshots:
defaults write com.apple.screencapture disable-shadow -bool true && killall SystemUIServer
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
-
Remove the
Where from
field fromvideo.mp4
, which was downloaded usingcurl
xattr -d 'com.apple.metadata:kMDItemWhereFroms' video.mp4
xcode-select
-
Enabling the Xcode Beta command line tools
sudo xcode-select --switch /Applications/Xcode-beta.app/
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
sips -r 90 'image.png'
-
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 itsPID
: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 disabledlaunchctl 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.
-
Printing the system root
launchctl print system
-
Printing details about a particular service within the root domain
launchctl print system/com.example.service
For your processes: if it's not in the system domain it's probably in the domain of that particular user.
-
Checking the domain of a particular user
launchctl print user/<uid>/ launchctl print user/<uid>/com.example.useragent
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
-
Enable a daemon service
launchctl enable user/$UID/com.tommy.foo
-
Disable a daemon service
launchctl disable user/$UID/com.tommy.foo
-
Launch a daemon service
launchctl kickstart
-
Launch any executable file with arguments as a launchctl
launchctl submit -l -- /path/to/executable 'arg1' 'arg2' 'arg3'
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