Back to Blog

Clipboard, Spotlight & Disk Tools from the Terminal — Zsh #28

Sandy LaneSandy Lane

Video: Clipboard, Spotlight & Disk Tools from the Terminal — Zsh #28 by Taught by Celeste AI - AI Coding Coach

Take the quiz on the full lesson page
Test what you've read · interactive walkthrough

Zsh Lesson 28: macOS Tricks — Clipboard, Spotlight, Disk Tools

pbcopy and pbpaste for clipboard. mdfind searches Spotlight from terminal. open launches files/URLs. say does text-to-speech. caffeinate prevents sleep. screencapture for screenshots. diskutil for disk management. macOS gives you the GUI features at the command line.

This lesson covers tools that ship with macOS and connect the terminal to the rest of the OS.

pbcopy / pbpaste: the clipboard

echo "Hello" | pbcopy
pbpaste
# Hello

# File contents to clipboard
cat report.txt | pbcopy

# Sort lines and copy result
sort -u file.txt | pbcopy

# Pipeline
awk -F, '{print $1}' data.csv | pbcopy

# Check
pbpaste | wc -l

pbcopy reads stdin, writes to clipboard. pbpaste writes clipboard to stdout. The clipboard is text by default; for images, use AppleScript or osascript.

The Linux equivalents are xclip or xsel; on Wayland, wl-copy and wl-paste. macOS ships them under pb* (pasteboard).

open: launch anything

open file.pdf            # default app
open .                   # current dir in Finder
open /Applications       # a directory
open https://example.com # URL in default browser
open -a "TextEdit" file.txt    # specific app
open -e file.txt         # TextEdit shortcut
open -R file.txt         # reveal in Finder (highlight)

open is one of the most useful macOS-specific commands. From terminal to GUI in one word.

say: text-to-speech

say "Hello from the terminal"
say -v Samantha "Custom voice"
say -v ?            # list voices
say -f speech.txt   # read from file

# Silly: morse code
say -i "Hello"

# Speak the time
say "$(date '+It is %I:%M %p')"

Useful for notifying yourself of long-running task completion:

slow_command && say "Done"

caffeinate: prevent sleep

caffeinate              # keep awake until Ctrl-C
caffeinate -t 600       # keep awake for 600 seconds
caffeinate make build   # keep awake while command runs

Useful for long-running tasks where you don't want the laptop to sleep.

Modes:

  • -d — display sleep prevented.
  • -i — system idle sleep prevented.
  • -s — system sleep prevented (when on AC).
  • -u — user is active assertion.

For a one-line "stay awake until I close the terminal":

caffeinate -dim &

screencapture: take screenshots

screencapture out.png              # interactive: click or drag
screencapture -i out.png           # interactive (default)
screencapture -x out.png           # silent (no shutter sound)
screencapture -t jpg out.jpg       # set format
screencapture -T 5 out.png         # 5 second delay
screencapture -W out.png           # window mode
screencapture -R 0,0,800,600 out.png   # specific rectangle

Same thing the GUI Cmd-Shift-4 does, scriptable.

mdfind: Spotlight from terminal

mdfind "annual report"           # full-text search across Mac
mdfind -name "*.pdf"              # filename search
mdfind -onlyin ~/Documents "tax"  # search a specific folder

# Spotlight metadata queries
mdfind "kMDItemFSName == '*.csv'"
mdfind "kMDItemContentType == 'public.image' && kMDItemFSSize > 1000000"

mdfind uses the Spotlight index — instant for files Spotlight has indexed. Way faster than find for "where's that PDF I downloaded?"

mdls: file metadata

mdls report.pdf
# Shows: name, size, type, dates, kMDItem* attributes

mdls -name kMDItemFSName -name kMDItemFSSize -name kMDItemContentType report.pdf

mdls shows Spotlight metadata for a file. Filter with -name attribute.

diskutil: disk management

diskutil list                       # all disks and partitions
diskutil info /                     # info about a volume
diskutil info /Volumes/MyDrive
diskutil eject /Volumes/USB
diskutil mount disk2s1
diskutil unmount /Volumes/Foo
diskutil verifyDisk disk2
diskutil repairDisk disk2

# Erase (DESTRUCTIVE)
# diskutil eraseDisk JHFS+ NewName disk2

diskutil is what Disk Utility GUI uses underneath. Useful for scripting drive operations.

Identifiers are like disk2, disk2s1 (slice 1). Always double-check before destructive operations — wrong identifier wipes the wrong drive.

hdiutil: disk images

# Create a disk image
hdiutil create -size 100m -fs HFS+ -volname MyVol disk.dmg

# Mount
hdiutil mount disk.dmg              # mounts at /Volumes/MyVol
hdiutil unmount /Volumes/MyVol

# Convert formats
hdiutil convert disk.dmg -format UDRO -o readonly.dmg
hdiutil convert disk.dmg -format UDZO -o compressed.dmg

# Encrypted dmg
hdiutil create -encryption AES-256 -size 100m -fs APFS -volname Secure secure.dmg

For backups, transfers, or carrying files in encrypted form.

defaults: read/write app preferences

# Read
defaults read com.apple.dock orientation
defaults read NSGlobalDomain AppleInterfaceStyle

# Write
defaults write com.apple.finder AppleShowAllFiles YES
defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false

# Restart Dock to apply Dock changes
killall Dock

Most macOS app preferences are stored in ~/Library/Preferences/*.plist. defaults reads and writes them.

Common tweaks:

# Show hidden files in Finder
defaults write com.apple.finder AppleShowAllFiles YES; killall Finder

# Disable smart quotes (helpful for code)
defaults write NSGlobalDomain NSAutomaticQuoteSubstitutionEnabled -bool false

# Faster key repeat
defaults write NSGlobalDomain KeyRepeat -int 1
defaults write NSGlobalDomain InitialKeyRepeat -int 10

# Show full path in Finder window title
defaults write com.apple.finder _FXShowPosixPathInTitle -bool true; killall Finder

osascript: AppleScript / JXA

osascript -e 'tell app "Safari" to make new document'
osascript -e 'display notification "Hello" with title "From Terminal"'
osascript -e 'set volume output volume 50'

# Multi-line
osascript <<'EOF'
tell application "System Events"
  set frontApp to name of first process whose frontmost is true
end tell
return frontApp
EOF

osascript runs AppleScript. From terminal you can drive any scriptable app — Safari, Mail, Calendar, OmniFocus, etc.

For modern JavaScript instead of AppleScript:

osascript -l JavaScript -e 'Application("Safari").windows[0].name();'

launchctl: load services (recap from L24)

launchctl list | grep myapp
launchctl load ~/Library/LaunchAgents/com.example.myapp.plist
launchctl unload ~/Library/LaunchAgents/com.example.myapp.plist

Already covered in lesson 24.

softwareupdate: macOS updates

softwareupdate --list                  # list available updates
softwareupdate -i -a                   # install all
softwareupdate -i "macOS Big Sur"      # specific update
softwareupdate --install-rosetta       # install Rosetta

CLI access to System Settings updates. Useful for headless servers.

brew: package manager

Not stock macOS, but everyone installs it:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

brew install fd ripgrep jq tmux
brew upgrade
brew search docker
brew info git
brew list
brew uninstall postgresql

Homebrew is the de facto macOS package manager. Get familiar with it.

A practical macOS automation

#!/usr/bin/env zsh
set -euo pipefail

# Download a file, checksum, notify

URL="$1"
EXPECTED_HASH="$2"

cd "$HOME/Downloads"
curl -L -O "$URL"
file=$(basename "$URL")

actual=$(shasum -a 256 "$file" | awk '{print $1}')

if [[ "$actual" == "$EXPECTED_HASH" ]]; then
  osascript -e "display notification \"$file verified\" with title \"Download\""
  open -R "$file"   # reveal in Finder
else
  osascript -e "display notification \"$file CHECKSUM MISMATCH\" with title \"Download\""
  rm -i "$file"
  exit 1
fi

Combines curl, shasum, AppleScript notifications, Finder integration. The kind of automation that rewards macOS-specific knowledge.

Common stumbles

open opens the wrong app. Each file extension has a default app — check with "Get Info" → "Open with." Or open -a "App Name" to override.

pbcopy doesn't include trailing newline. echo adds one; printf '%s' doesn't. Be aware when pasting into apps.

mdfind returns no results. Spotlight may not have indexed that directory. Re-index with sudo mdutil -E /.

Permission errors. macOS sandboxes lots of directories by default — Documents, Desktop, Downloads, etc. Grant your terminal "Full Disk Access" in System Settings → Privacy & Security.

defaults change doesn't apply. Many apps cache. killall AppName to force restart.

screencapture -i doesn't show the crosshair. Terminal may be obscured. Try screencapture -i -x out.png (silent + interactive).

diskutil eraseDisk on the wrong disk. Disaster. Always diskutil list first; verify the identifier; use diskutil info diskN to confirm.

say interrupting. Each say queues. To kill: killall say.

What's next

Lesson 29: Git workflows. Aliases, branches, hooks, statistics from the terminal.

Recap

pbcopy/pbpaste for clipboard. open file/url/. for "open in default app." say "text" for TTS. caffeinate to prevent sleep. screencapture for screenshots. mdfind queries Spotlight. mdls shows file metadata. diskutil and hdiutil for drives and disk images. defaults reads/writes app preferences. osascript for AppleScript automation. softwareupdate for system updates.

Next lesson: Git workflows.

Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.