macOS CLI β Command Line Reference#
Shell & environment#
echo $SHELL # current shell (/bin/zsh on modern macOS)
chsh -s /bin/zsh # switch to zsh
chsh -s /bin/bash # switch to bash
echo $PATH # view PATH
export PATH="/usr/local/bin:$PATH" # prepend to PATH (add to ~/.zshrc to persist)
env # all environment variables
printenv HOME # single variable
source ~/.zshrc # reload zsh config
exec $SHELL -l # reload shell login
File & directory#
ls -la # long listing, hidden files
ls -lhS # sort by size, human-readable
ls -lt # sort by modification time
ls -1 # one file per line
pwd # print working directory
cd - # go to previous directory
cd ~ # go to home
mkdir -p a/b/c # create nested directories
rmdir dir # remove empty directory
rm -rf dir # remove directory and contents (careful!)
cp -R src/ dst/ # copy directory recursively
cp -a src/ dst/ # preserve attributes + recursive
mv old new # move / rename
ln -s /path/to/target link # create symlink
readlink -f link # resolve symlink to real path
touch file.txt # create empty file / update timestamp
file image.png # detect file type
du -sh * # sizes of items in current dir
du -sh ~/Downloads # size of a folder
df -h # disk free, human readable
Finder & open#
open . # open current dir in Finder
open file.pdf # open with default app
open -a "Visual Studio Code" . # open with specific app
open -R file.txt # reveal file in Finder
open https://example.com # open URL in default browser
# Reveal hidden files in Finder
defaults write com.apple.Finder AppleShowAllFiles true
killall Finder
# Show/hide Desktop icons
defaults write com.apple.finder CreateDesktop false && killall Finder
defaults write com.apple.finder CreateDesktop true && killall Finder
Clipboard#
pbcopy < file.txt # copy file contents to clipboard
pbpaste > file.txt # paste clipboard to file
echo "hello" | pbcopy # copy command output
pbpaste # print clipboard to stdout
# Useful combos
pwd | pbcopy # copy current path
cat ~/.ssh/id_ed25519.pub | pbcopy # copy SSH public key
Text-to-speech#
say "Hello, world" # speak text
say -v ? # list available voices
say -v Samantha "macOS is great" # use specific voice
say -r 180 "fast speech" # words per minute
say -f script.txt # read from file
say -o output.aiff "record this" # save to audio file
Processes#
ps aux # all processes
ps aux | grep python # filter by name
top # interactive process viewer
htop # better top (brew install htop)
kill PID # send SIGTERM
kill -9 PID # send SIGKILL (force)
killall "App Name" # kill by name
pkill -f pattern # kill by pattern match
lsof -i :8080 # what process is on port 8080
lsof -p PID # files open by PID
lsof +D /path # processes using a directory
# Activity Monitor from terminal
sudo fs_usage PID # file system usage
sudo dtrace -n 'syscall:::entry { @[execname] = count(); }' # syscall stats
System info#
sw_vers # macOS version
sw_vers -productVersion # e.g. 15.4.1
uname -a # kernel info
hostname # computer name
scutil --get ComputerName # friendly computer name
scutil --get LocalHostName # local hostname
system_profiler SPHardwareDataType # hardware overview
system_profiler SPSoftwareDataType # software overview
sysctl -n hw.physicalcpu # physical CPU count
sysctl -n hw.logicalcpu # logical CPU count (threads)
sysctl -n hw.memsize # RAM in bytes
sysctl -n machdep.cpu.brand_string # CPU model name
# Architecture
uname -m # arm64 (Apple Silicon) or x86_64 (Intel)
arch # same
Homebrew#
# Install
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install ripgrep # install a formula
brew install --cask firefox # install a GUI app
brew uninstall ripgrep # remove
brew upgrade # upgrade all
brew upgrade ripgrep # upgrade specific
brew update # update Homebrew itself
brew list # installed formulae
brew list --cask # installed casks
brew info ripgrep # info about a package
brew search grep # search packages
brew outdated # packages with updates
brew doctor # diagnose issues
brew cleanup # remove old versions
brew deps --tree ripgrep # dependency tree
brew services list # managed services
brew services start postgresql # start a service
brew services stop postgresql # stop
brew services restart postgresql # restart
Networking#
ifconfig # network interfaces (legacy)
networksetup -listallnetworkservices # list interfaces
networksetup -getinfo Wi-Fi # IP, subnet, gateway for Wi-Fi
ipconfig getifaddr en0 # IP of interface en0
ipconfig getifaddr en1 # IP of interface en1 (Wi-Fi)
curl ifconfig.me # public IP
ping -c 4 google.com # 4 ping packets
traceroute google.com # route tracing
nslookup github.com # DNS lookup
dig github.com # detailed DNS
host github.com # simple DNS
netstat -an | grep LISTEN # listening ports
lsof -i -P | grep LISTEN # listening ports with process names
lsof -i tcp:443 # what's on port 443
# Wi-Fi
airport -s # scan nearby networks (legacy)
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s
networksetup -setairportpower en0 off # turn Wi-Fi off
networksetup -setairportpower en0 on # turn Wi-Fi on
# DNS flush
sudo dscacheutil -flushcache && sudo killall -HUP mDNSResponder
diskutil#
diskutil list # all disks and partitions
diskutil info disk0 # info for disk0
diskutil info / # info for root volume
diskutil eraseDisk APFS "MyDisk" disk2 # erase to APFS
diskutil eraseVolume ExFAT "USB" disk2s1 # erase a volume
diskutil mount disk2s1 # mount a volume
diskutil unmount disk2s1 # unmount a volume
diskutil eject disk2 # eject removable disk
# Verify / repair
diskutil verifyVolume /
diskutil repairVolume /
# APFS
diskutil apfs list # APFS containers and volumes
diskutil apfs addVolume disk3s1 APFS "Scratch" # add APFS volume
defaults (preference system)#
defaults read # dump ALL user defaults
defaults read com.apple.finder # read Finder prefs
defaults read com.apple.dock # read Dock prefs
defaults write com.apple.dock autohide -bool true # auto-hide dock
defaults write com.apple.dock tilesize -int 36 # dock icon size
defaults write com.apple.dock orientation -string left # dock on left
killall Dock # apply dock changes
defaults write com.apple.screensaver askForPasswordDelay -int 0 # lock immediately
# Key repeat
defaults write -g InitialKeyRepeat -int 15 # 15 = ~225ms
defaults write -g KeyRepeat -int 2 # 2 = ~30ms
# Log out / in to apply
defaults delete com.apple.dock # reset Dock to factory
launchctl & services#
launchctl list # running launch agents/daemons
launchctl list | grep com.apple # Apple services only
# Load / unload a plist
launchctl load ~/Library/LaunchAgents/com.example.agent.plist
launchctl unload ~/Library/LaunchAgents/com.example.agent.plist
# Modern bootstrap (macOS 10.11+)
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.example.agent.plist
launchctl bootout gui/$(id -u)/com.example.agent
# Service locations
# ~/Library/LaunchAgents/ user agents (run when user logged in)
# /Library/LaunchAgents/ system agents (any logged-in user)
# /Library/LaunchDaemons/ system daemons (root, no GUI)
# /System/Library/LaunchDaemons/ Apple daemons (don't touch)
Security & permissions#
chmod +x script.sh # make executable
chmod 644 file.txt # rw-r--r--
chmod -R 755 dir/ # recursive
chown user:group file # change owner
sudo chown -R $(whoami) /usr/local # take ownership
# Extended attributes & quarantine
xattr -l file.dmg # list extended attributes
xattr -d com.apple.quarantine file.dmg # remove quarantine flag
xattr -cr ./app.app # clear all xattrs recursively
# Gatekeeper
spctl --assess --type exec app.app # check Gatekeeper status
sudo spctl --master-disable # disable Gatekeeper (not recommended)
sudo spctl --master-enable # re-enable Gatekeeper
# Keychain
security find-internet-password -s github.com # find stored password
security find-generic-password -s "My Service" -w # get password value
# File Vault
fdesetup status # FileVault status
Archives & compression#
# zip
zip archive.zip file1 file2 # create zip
zip -r archive.zip dir/ # zip directory
unzip archive.zip # extract
unzip -l archive.zip # list contents
# tar
tar -czf archive.tar.gz dir/ # create gzip tar
tar -xzf archive.tar.gz # extract gzip tar
tar -cjf archive.tar.bz2 dir/ # create bzip2 tar
tar -xjf archive.tar.bz2 # extract bzip2
tar -tf archive.tar.gz # list contents
tar -xzf archive.tar.gz -C /dest/ # extract to specific dir
# ditto (macOS-native, preserves resource forks)
ditto src/ dst/ # copy preserving metadata
ditto -ck --sequesterRsrc dir/ archive.zip # create zip with Mac metadata
ditto -xk archive.zip dst/ # extract zip preserving Mac metadata
Text & search#
grep -r "pattern" . # recursive search
grep -rn "pattern" . --include="*.py" # with line numbers, filter ext
grep -rl "pattern" . # list files only
find . -name "*.log" -mtime -7 # files modified last 7 days
find . -name "*.DS_Store" -delete # remove .DS_Store files
find . -type f -size +10M # files over 10 MB
mdfind "query" # Spotlight search from terminal
mdfind -name "report.pdf" # find by filename via Spotlight
mdfind "kMDItemContentType == 'public.png'" # find by UTI
# awk, sed, sort, uniq β same as Linux
awk '{print $1}' file.txt
sed -i '' 's/old/new/g' file.txt # macOS sed requires '' after -i
sort -u file.txt # sort + deduplicate
mdls file.pdf # all metadata for a file
mdls -name kMDItemContentType file.pdf # specific attribute
# Index control
sudo mdutil -i on / # enable Spotlight indexing
sudo mdutil -i off /Volumes/USB # disable for a volume
sudo mdutil -E / # erase and rebuild index
mdutil -s / # indexing status
Screenshots (command line)#
screencapture -x screen.png # screenshot, no shutter sound
screencapture -T 5 delayed.png # 5-second delay
screencapture -w window.png # click to capture a window
screencapture -s selection.png # drag to select region
screencapture -c # capture to clipboard
screencapture -t jpg output.jpg # JPEG format
screencapture -R 0,0,1280,720 region.png # specific region (x,y,w,h)
Power management#
pmset -g # current power settings
pmset -g assertions # power assertions (what's preventing sleep)
pmset -g log | tail -50 # recent power events
caffeinate # prevent sleep (ctrl-C to stop)
caffeinate -t 3600 # prevent sleep for 1 hour
caffeinate -i make # prevent sleep while command runs
caffeinate -d # prevent display sleep specifically
sudo pmset sleep 0 # disable sleep (plugged in)
sudo pmset -b sleep 10 # sleep after 10 min on battery
# Shutdown / restart
sudo shutdown -h now # shutdown immediately
sudo shutdown -r now # restart immediately
sudo shutdown -h +60 # shutdown in 60 minutes
# System events
osascript -e 'display notification "Done!" with title "Build"' # notification
osascript -e 'tell application "Finder" to empty trash' # empty trash
# Pasteboard / Universal Clipboard
pbcopy; pbpaste # see Clipboard section above
# Quick Look from terminal
qlmanage -p file.png # preview a file
# System sound
afplay /System/Library/Sounds/Ping.aiff # play a system sound
afinfo /System/Library/Sounds/Ping.aiff # file info
# Sharing
networksetup -setnetworkserviceenabled "Ethernet" on # enable interface
scutil --set ComputerName "MyMac" # rename computer
# xcode cli tools
xcode-select --install # install Command Line Tools
xcode-select -p # path to active dev tools
xcrun --find clang # find a specific tool
.DS_Store & housekeeping#
# Remove .DS_Store everywhere
find . -name ".DS_Store" -delete
# Prevent .DS_Store on network shares
defaults write com.apple.desktopservices DSDontWriteNetworkStores true
# Clear icon cache
sudo find /private/var/folders -name "com.apple.dock.iconcache" -delete
sudo find /private/var/folders -name "com.apple.iconservices" -delete
killall Dock
# Clean up system caches (careful)
sudo periodic daily weekly monthly # run maintenance scripts
Common recipes#
# Copy SSH key to clipboard
cat ~/.ssh/id_ed25519.pub | pbcopy
# List largest files in current directory
du -sh * | sort -rh | head -10
# Kill process on port 3000
lsof -ti:3000 | xargs kill -9
# Watch a file for changes
fswatch -o file.txt | xargs -n1 -I{} echo "changed"
# Recursively fix permissions
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
# Monthly disk usage report
du -sh ~/Documents ~/Downloads ~/Desktop ~/Movies ~/Music ~/Pictures
# Remove quarantine from downloaded app
xattr -dr com.apple.quarantine /Applications/MyApp.app
# Check if a port is open
nc -zv google.com 443
# Flush DNS cache
sudo dscacheutil -flushcache && sudo killall -HUP mDNSResponder
# Convert HEIC to JPEG (requires sips)
for f in *.heic; do sips -s format jpeg "$f" --out "${f%.heic}.jpg"; done