larz0/awesome-osx-command-line
Use your OS X terminal shell to do awesome things.
A curated list of shell commands and tools specific to OS X.
“You don’t have to know everything. You simply need to know where to find it when necessary.” (John Brunner)
If you want to contribute, you are highly encouraged to do so. Please read the contribution guidelines.
Table of Contents
- Appearance
- Applications
- Backup
- Developer
- Disks and Volumes
- Dock
- Documents
- Finder
- Fonts
- Hardware
- Input Devices
- Media
- Networking
- Package Managers
- Printing
- Security
- Search
- System
- Terminal
Appearance
Transparency
Reduce Transparency in Menu and Windows
defaults write com.apple.universalaccess reduceTransparency -bool trueRestore Default Transparency in Menu and Windows
defaults write com.apple.universalaccess reduceTransparency -bool falseWallpaper
Set Wallpaper
Up to Mountain Lion:
osascript -e 'tell application "Finder" to set desktop picture to POSIX file "/path/to/picture.jpg"'Since Mavericks:
sqlite3 ~/Library/Application\ Support/Dock/desktoppicture.db "update data set value = '/path/to/picture.jpg'" && killall DockApplications
App Store
List All Apps Downloaded from App Store
find /Applications -path '*Contents/_MASReceipt/receipt' -maxdepth 4 -print |\sed 's#.app/Contents/_MASReceipt/receipt#.app#g; s#/Applications/##'Apple Remote Desktop
Remove Apple Remote Desktop Settings
sudo rm -rf /var/db/RemoteManagement ; \
sudo defaults delete /Library/Preferences/com.apple.RemoteDesktop.plist ; \
defaults delete ~/Library/Preferences/com.apple.RemoteDesktop.plist ; \
sudo rm -r /Library/Application\ Support/Apple/Remote\ Desktop/ ; \
rm -r ~/Library/Application\ Support/Remote\ Desktop/ ; \
rm -r ~/Library/Containers/com.apple.RemoteDesktopiTunes
Stop Responding to the Keyboard Media Keys
launchctl unload -w /System/Library/LaunchAgents/com.apple.rcd.plistSafari
Enable Develop Menu and Web Inspector
defaults write com.apple.Safari IncludeInternalDebugMenu -bool true && \
defaults write com.apple.Safari IncludeDevelopMenu -bool true && \
defaults write com.apple.Safari WebKitDeveloperExtrasEnabledPreferenceKey -bool true && \
defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2DeveloperExtrasEnabled -bool true && \
defaults write NSGlobalDomain WebKitDeveloperExtras -bool trueSketch
Export Compact SVGs
defaults write com.bohemiancoding.sketch3 exportCompactSVG -bool yesTextEdit
Use Plain Text Mode as Default
defaults write com.apple.TextEdit RichText -int 0Backup
Time Machine
Change Backup Interval
This changes the interval to 30 minutes. The integer value is the time in seconds.
sudo defaults write /System/Library/Launch Daemons/com.apple.backupd-auto StartInterval -int 1800Disable Local Time Machine Backups
hash tmutil &> /dev/null && sudo tmutil disablelocalPrevent Time Machine From Prompting to Use New Hard Drives as Backup Volume
defaults write com.apple.TimeMachine DoNotOfferNewDisksForBackup -bool trueDeveloper
App Icons
Create App Icon
Function to quickly create an application icon from 1024px master file.
function mkicns() {
if [[ -z "$@" ]]; then
echo "Input file missing"
else
filename=${1%.*}
mkdir $filename.iconset
sips -z 16 16 $1 --out $filename.iconset/icon_16x16.png
sips -z 32 32 $1 --out $filename.iconset/icon_16x16@2x.png
sips -z 32 32 $1 --out $filename.iconset/icon_32x32.png
sips -z 64 64 $1 --out $filename.iconset/icon_32x32@2x.png
sips -z 128 128 $1 --out $filename.iconset/icon_128x128.png
sips -z 256 256 $1 --out $filename.iconset/icon_128x128@2x.png
sips -z 256 256 $1 --out $filename.iconset/icon_256x256.png
sips -z 512 512 $1 --out $filename.iconset/icon_256x256@2x.png
sips -z 512 512 $1 --out $filename.iconset/icon_512x512.png
cp $1 $filename.iconset/icon_512x512@2x.png
iconutil -c icns $filename.iconset
rm -r $filename.iconset
fi
}Vim
Compile Sane Vim
Compiling MacVim via Homebrew with all bells and whistles, including overriding system Vim.
brew install macvim --HEAD --with-cscope --with-lua --with-override-system-vim --with-luajit --with-pythonNeoVim
Install the development version of this modern Vim drop-in alternative via Homebrew.
brew tap neovim/neovim && \
brew install --HEAD neovimXcode
Install Command Line Tools Without Xcode
xcode-select --installRemove All Unavailable Simulators
xcrun simctl delete unavailableDisks and Volumes
Disable Sudden Motion Sensor
Leaving this turned on is useless when you're using SSDs.
sudo pmset -a sms 0Eject All Mountable Volumes
The only reliable way to do this is by sending an AppleScript command to Finder.
osascript -e 'tell application "Finder" to eject (every disk whose ejectable is true)'Repair File Permissions
You don't have to use the Disk Utility GUI for this.
sudo diskutil repairPermissions /Beginning with OS X El Capitan, system file permissions are automatically protected. It's no longer necessary to verify or repair permissions with Disk Utility. (Source)
Set Boot Volume
bless --mount "/path/to/mounted/volume" --setBootShow All Attached Disks and Partitions
diskutil listView File System Usage
A contiuous stream of file system access info.
sudo fs_usageDisk Images
Disable Disk Image Verification
defaults write com.apple.frameworks.diskimages skip-verify -bool true && \
defaults write com.apple.frameworks.diskimages skip-verify-locked -bool true && \
defaults write com.apple.frameworks.diskimages skip-verify-remote -bool trueMake Volume OS X Bootable
bless --folder "/path/to/mounted/volume/System/Library/CoreServices" --bootinfo --bootefiMount Disk Image
hdiutil attach /path/to/diskimage.dmgUnmount Disk Image
hdiutil detach /dev/disk2s1Write Disk Image to Volume
Like the Disk Utility "Restore" function.
sudo asr -restore -noverify -source /path/to/diskimage.dmg -target /Volumes/VolumeToRestoreToDock
Add a Stack with Recent Applications
defaults write com.apple.dock persistent-others -array-add '{ "tile-data" = { "list-type" = 1; }; "tile-type" = "recents-tile"; }' && \
killall DockDocuments
Convert File to HTML
Supported formats are plain text, rich text (rtf) and Microsoft Word (doc/docx).
textutil -convert html file.extFinder
Files and Folders
Clear All ACLs
sudo chmod -RN /path/to/folderHide Folder in Finder
chflags hidden /path/to/folder/Show All File Extensions
defaults write NSGlobalDomain AppleShowAllExtensions -bool trueShow All Hidden Files
defaults write com.apple.finder AppleShowAllFiles trueRestore Default File Visibility
defaults write com.apple.finder AppleShowAllFiles falseRemove Protected Flag
sudo chflags -R nouchg /path/to/file/or/folderShow Full Path in Finder Title
defaults write com.apple.finder _FXShowPosixPathInTitle -bool trueUnhide User Library Folder
chflags nohidden ~/LibraryLayout
Disable Smooth Scrolling
Useful if you’re on an older Mac that messes up the animation.
defaults write NSGlobalDomain NSScrollAnimationEnabled -bool falseEnable Smooth Scrolling
Revert back to standard behavior.
defaults write NSGlobalDomain NSScrollAnimationEnabled -bool trueDisable Rubberband Scrolling
defaults write -g NSScrollViewRubberbanding -bool falseEnable Rubberband Scrolling
Revert to default behavior.
defaults write -g NSScrollViewRubberbanding -bool trueExpand Save Panel by Default
defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode -bool true && \
defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode2 -bool trueHide All Desktop Icons
defaults write com.apple.finder CreateDesktop -bool false && killall FinderShow All Desktop Icons
defaults write com.apple.finder CreateDesktop -bool true && killall FinderShow Path Bar
defaults write com.apple.finder ShowPathbar -bool trueScrollbar Visibility
Possible values: WhenScrolling, Automatic and Always.
defaults write NSGlobalDomain AppleShowScrollBars -string "Always"Show Status Bar
defaults write com.apple.finder ShowStatusBar -bool trueSave to Disk by Default
Sets default save target to be a local disk, not iCloud.
defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool falseSet Current Folder as Default Search Scope
defaults write com.apple.finder FXDefaultSearchScope -string "SCcf"Set Default Finder Location to Home Folder
defaults write com.apple.finder NewWindowTarget -string "PfLo" && \
defaults write com.apple.finder NewWindowTargetPath -string "file://${HOME}"Set Sidebar Icon Size
Sets size to 'medium'.
defaults write NSGlobalDomain NSTableViewDefaultSizeMode -int 2Metadata Files
Disable Creation of Metadata Files on Network Volumes
Avoids creation of .DS_Store and AppleDouble files.
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool trueDisable Creation of Metadata Files on USB Volumes
Avoids creation of .DS_Store and AppleDouble files.
defaults write com.apple.desktopservices DSDontWriteUSBStores -bool trueOpening Things
Change Working Directory to Finder Path
If multiple windows are open, it chooses the top-most one.
cd "$(osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)')"Open URL
open http://www.github.comOpen File
open README.mdOpen Applications
You can open applications using -a.
open -a "Google Chrome" http://www.github.comOpen Folder
open /path/to/folder/Open Current Folder
open .Fonts
Clear Font Cache for Current User
To clear font caches for all users, put sudo in front of this command.
atsutil databases -removeUser && \
atsutil server -shutdown && \
atsutil server -pingHardware
Hardware Information
List All Hardware Ports
networksetup -listallhardwareportsRemaining Battery Percentage
pmset -g batt | egrep "([0-9]+\%).*" -o --colour=auto | cut -f1 -d';'Remaining Battery Time
pmset -g batt | egrep "([0-9]+\%).*" -o --colour=auto | cut -f3 -d';'Show Connected Device's UDID
system_profiler SPUSBDataType | sed -n -e '/iPad/,/Serial/p' -e '/iPhone/,/Serial/p'Show Current Screen Resolution
system_profiler SPDisplaysDataType | grep ResolutionShow CPU Brand String
sysctl -n machdep.cpu.brand_stringPower Management
Prevent System Sleep
Prevent sleep for 1 hour:
caffeinate -u -t 3600Show All Power Management Settings
sudo pmset -gPut Display to Sleep After 15 Minutes of Inactivity
sudo pmset displaysleep 15Put Computer to Sleep After 30 Minutes of Inactivity
sudo pmset sleep 30Check System Sleep Idle Time
sudo systemsetup -getcomputersleepSet System Sleep Idle Time to 60 Minutes
sudo systemsetup -setcomputersleep 60Turn Off System Sleep Completely
sudo systemsetup -setcomputersleep NeverEnable Chime when Charging
Play iOS charging sound when MagSafe is connected.
defaults write com.apple.PowerChime ChimeOnAllHardware -bool true && \
open /System/Library/CoreServices/PowerChime.appDisable Chime when Charging
defaults write com.apple.PowerChime ChimeOnAllHardware -bool false && \
open /System/Library/CoreServices/PowerChime.appInput Devices
Keyboard
Disable Auto-Correct
defaults write -g NSAutomaticSpellingCorrectionEnabled -bool falseEnable Auto-Correct
defaults write -g NSAutomaticSpellingCorrectionEnabled -bool trueShow Auto-Correct Setting
defaults read -g NSAutomaticSpellingCorrectionEnabledEnable Key Repeat
Disable the default "press and hold" behavior.
defaults write -g ApplePressAndHoldEnabled -bool falseSet Key Repeat Rate
Sets a very fast repeat rate, adjust to taste.
defaults write NSGlobalDomain KeyRepeat -int 0.02Media
Audio
Convert Audio File to iPhone Ringtone
afconvert input.mp3 ringtone.m4r -f m4afDisable Sound Effects on Boot
sudo nvram SystemAudioVolume=" "Mute Audio Output
osascript -e 'set volume output muted true'Set Audio Volume
osascript -e 'set volume 4'Play Audio File
You can play all audio formats that are natively supported by QuickTime.
afplay -q 1 filename.mp3Speak Text with System Default Voice
say 'All your base are belong to us!'Video
Auto-Play Videos in QuickTime Player
defaults write com.apple.QuickTimePlayerX MGPlayMovieOnOpen 1Networking
Bonjour
Disable Bonjour
sudo defaults write /System/Library/LaunchDaemons/com.apple.mDNSResponder ProgramArguments -array-add "-NoMulticastAdvertisements"Enable Bonjour
sudo defaults write /System/Library/LaunchDaemons/com.apple.mDNSResponder ProgramArguments -array "/usr/sbin/mDNSResponder" "-launchd"DHCP
Renew DHCP Lease
sudo ipconfig set en0 DHCPShow DHCP Info
ipconfig getpacket en0DNS
Clear DNS Cache
sudo dscacheutil -flushcache && \
sudo killall -HUP mDNSResponderHostname
Set Computer Name/Host Name
sudo scutil --set ComputerName "newhostname" && \
sudo scutil --set HostName "newhostname" && \
sudo scutil --set LocalHostName "newhostname" && \
sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName -string "newhostname"Networking Tools
Ping a Host to See Whether It’s Available
ping -o github.comTroubleshoot Routing Problems
traceroute github.comTCP/IP
Show Application Using a Certain Port
This outputs all applications currently using port 80.
sudo lsof -i :80Show External IP Address
dig +short myip.opendns.com @resolver1.opendns.comWi-Fi
Scan Available Access Points
Create a symbolic link to the airport command for easy access:
sudo ln -s /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport /usr/local/bin/airportRun a wireless scan:
airport -sShow Current SSID
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk '/ SSID/ {print substr($0, index($0, $2))}'Show Local IP Address
ipconfig getifaddr en0Show Wi-Fi Connection History
defaults read /Library/Preferences/SystemConfiguration/com.apple.airport.preferences | grep LastConnected -A 7Show Wi-Fi Network Passwords
Exchange SSID with the SSID of the access point you wish to query the password from.
security find-generic-password -D "AirPort network password" -a "SSID" -gwPackage Managers
- Fink - The full world of Unix Open Source software for Darwin.
- Homebrew - The missing package manager for OS X.
- MacPorts - Compile, install and upgrade either command-line, X11 or Aqua based open-source software.
Printing
Clear Print Queue
cancel -a -Expand Print Panel by Default
defaults write NSGlobalDomain PMPrintingExpandedStateForPrint -bool true && \
defaults write NSGlobalDomain PMPrintingExpandedStateForPrint2 -bool trueQuit Printer App After Print Jobs Complete
defaults write com.apple.print.PrintingPrefs "Quit When Finished" -bool trueSecurity
Gatekeeper
Add Gatekeeper Exception
spctl --add /path/to/Application.appRemove Gatekeeper Exception
spctl --remove /path/to/Application.appPasswords
Generate Secure Password and Copy to Clipboard
First, install pwgen via Homebrew, etc.
pwgen -Cs 20 1 | tr -d ' ' | tr -d '\n' | pbcopyPhysical Access
Lock Screen
/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspendWiping Data
Securely Remove File
srm /path/to/fileSecurely Remove Folder
srm -r /path/to/folder/Securely Remove Path (Force)
srm -rf /path/to/complete/destructionSearch
Find
Recursively Delete .DS_Store Files
find . -type f -name '*.DS_Store' -ls -deleteLocate
Build Locate Database
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plistSearch via Locate
The -i modifier makes the search case insensitive.
locate -i *.jpgSystem
AirDrop
Enable AirDrop over Ethernet and on Unsupported Macs
defaults write com.apple.NetworkBrowser BrowseAllInterfaces -bool trueAppleScript
Execute AppleScript
osascript /path/to/script.scptBasics
Restart
sudo rebootShutdown
sudo poweroffShow Build Number of OS
sw_versUptime
How long since your last restart.
uptimeClipboard
Copy data to Clipboard
cat whatever.txt | pbcopyConvert Tabs to Spaces for Clipboard Content
pbpaste | expand | pbcopyCopy data from Clipboard
pbpaste > whatever.txtSort and Strip Duplicate Lines from Clipboard Content
pbpaste | sort | uniq | pbcopyFileVault
Automatically Unlock FileVault on Restart
If FileVault is enabled on the current volume, it restarts the system, bypassing the initial unlock. The command may not work on all systems.
sudo fdesetup authrestartCheck FileVault Status
sudo fdesetup statusInformation/Reports
Generate Advanced System and Performance Report
sudo sysdiagnose -f ~/Desktop/Kernel Extensions
Load Kernel Extension
sudo kextload -b com.apple.driver.ExampleBundleUnload Kernel Extensions
sudo kextunload -b com.apple.driver.ExampleBundleLaunchAgents
Periodical Job Template
Run job every 5 minutes.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.example.touchsomefile</string>
<key>ProgramArguments</key>
<array>
<string>touch</string>
<string>/tmp/helloworld</string>
</array>
<key>StartInterval</key>
<integer>300</integer>
</dict>
</plist>Periodical via Calendar Interval Job Template
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.example.touchsomefile</string>
<key>ProgramArguments</key>
<array>
<string>touch</string>
<string>/tmp/helloworld</string>
</array>
<key>StartCalendarInterval</key>
<dict>
<key>Minute</key>
<integer>45</integer>
<key>Hour</key>
<integer>13</integer>
<key>Day</key>
<integer>7</integer>
</dict>
</dict>
</plist>Monitoring Folder Job Template
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.example.watchhostconfig</string>
<key>ProgramArguments</key>
<array>
<string>syslog</string>
<string>-s</string>
<string>-l</string>
<string>notice</string>
<string>somebody touched /etc/hostconfig</string>
</array>
<key>WatchPaths</key>
<array>
<string>/etc/hostconfig</string>
</array>
</dict>
</plist>LaunchServices
Rebuild LaunchServices Database
To be independent of OS X version, this relies on locate to find lsregister. If you do not have your locate database built yet, do it.
sudo $(locate lsregister) -kill -seed -rMemory Management
Purge memory cache
sudo purgeNotification Center
Disable Notification Center
launchctl unload -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plist && \
killall -9 NotificationCenterEnable Notification Center
launchctl load -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plistQuickLook
Preview via QuickLook
qlmanage -p /path/to/fileRoot User
Enable Root User
dsenablerootDisable Root User
dsenableroot -dSafe Mode Boot
Check Safe Mode Setting
nvram boot-argsEnable Safe Mode
sudo nvram boot-args="-x"Disable Safe Mode
sudo nvram boot-args=""Screenshots
Take Delayed Screenshot
Takes a screenshot as JPEG after 3 seconds and displays in Preview.
screencapture -T 3 -t jpg -P delayedpic.jpgSave Screenshots to Given Location
Sets location to ~/Desktop.
defaults write com.apple.screencapture location ~/Desktop && \
killall SystemUIServerSave Screenshots in Given Format
Sets format to png. Other options are bmp, gif, jpg, jpeg, pdf, tiff.
defaults write com.apple.screencapture type -string "png"Disable Shadow in Screenshots
defaults write com.apple.screencapture disable-shadow -bool true && \
killall SystemUIServerSoftware Installation
Install PKG
installer -pkg /path/to/installer.pkg -target /Software Update
Install All Available Software Updates
sudo softwareupdate -iaSet Software Update Check Interval
Set to check daily instead of weekly.
defaults write com.apple.SoftwareUpdate ScheduleFrequency -int 1Show Available Software Updates
sudo softwareupdate -lSpotlight
Disable Indexing
mdutil -i off -d /path/to/volumeEnable Indexing
mdutil -i on /path/to/volumeErase Spotlight Index and Rebuild
mdutil -E /path/to/volumeSearch via Spotlight
mdfind -name 'searchterm'System Integrity Protection
Disable System Integrity Protection
Reboot while holding Cmd + R, open the Terminal application and enter:
csrutil disable && rebootEnable System Integrity Protection
Reboot while holding Cmd + R, open the Terminal application and enter:
csrutil enable && rebootTerminal
Ring Terminal Bell
Rings the terminal bell (if enabled) and puts a badge on it.
tput belAlternative Terminals
- iTerm 2 - A better Terminal.app.
- TotalTerminal - A system-wide terminal available on a hot-key.
Shells
Bash
Install the latest version and set as current users' default shell:
brew install bash && \
sudo echo $(brew --prefix)/bin/bash >> /etc/shells && \
chsh -s $(brew --prefix)/bin/bash- Homepage - The default shell for OS X and most other Unix-based operating systems.
fish
Install the latest version and set as current users' default shell:
brew install fish && \
chsh -s $(brew --prefix)/bin/fish- Homepage - A smart and user-friendly command line
shell for OS X, Linux, and the rest of the family. - The Fishshell Framework - Provides core infrastructure to allow you to install packages which extend or modify the look of your shell.
Zsh
Install the latest version and set as current users' default shell:
brew install zsh && \
chsh -s $(brew --prefix)/bin/zsh- Homepage - Zsh is a shell designed for interactive use, although it is also a powerful scripting language.
- Oh My Zsh - An open source, community-driven framework for managing your Zsh configuration.
- Prezto - A speedy Zsh framework. Enriches the command line interface environment with sane defaults, aliases, functions, auto completion, and prompt themes.
Terminal Fonts
- Anonymous Pro - A family of four fixed-width fonts designed with coding in mind.
- Hack - Hack is hand groomed and optically balanced to be your go-to code face.
- Inconsolata - A monospace font, designed for code listings and the like.
- Input - A flexible system of fonts designed specifically for code.
- Meslo - Customized version of Apple's Menlo font.
- Source Code Pro - A monospaced font family for user interfaces and coding environments.
License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
