The Terminal app in macOS is a powerful tool that provides direct access to the Unix underpinnings of your Mac. While many users never need to venture into this text-based interface, power users can leverage Terminal commands to accomplish tasks more efficiently, access hidden features, and gain greater control over their system. In this article, we'll explore some advanced Terminal commands and scripts that can enhance your Mac experience.
Caution
The Terminal provides powerful commands that can modify your system in significant ways. Always use caution when entering commands, and make sure you understand what a command does before executing it. Consider backing up your system before making significant changes.
Terminal Basics for Beginners
Before diving into advanced commands, let's quickly review some Terminal basics for those who might be new to the command line:
- Open Terminal from Applications > Utilities > Terminal
- Commands are case-sensitive
- Press Return/Enter to execute a command
- Use Tab for auto-completion of file and folder names
- Press Ctrl+C to cancel a running command
- Use the up and down arrow keys to navigate through command history
Pro Tip
Consider installing a Terminal alternative like iTerm2, which offers additional features such as split panes, better search, and more customization options.
Basic Navigation Commands
pwd # Print working directory (shows current location)
ls # List files and directories
cd [directory] # Change directory
cd .. # Move up one directory
cd ~ # Go to home directory
clear # Clear the terminal screen
1. System Information Commands
These commands help you gather detailed information about your Mac's hardware and software.
Get Detailed System Information
system_profiler SPHardwareDataType # Hardware overview
sysctl -n machdep.cpu.brand_string # CPU information
system_profiler SPDisplaysDataType # Display information
system_profiler SPStorageDataType # Storage information
system_profiler SPNetworkDataType # Network information
For a comprehensive system report, you can use:
system_profiler -detailLevel mini > ~/Desktop/system_report.txt
This command generates a system report and saves it to your desktop. You can change "mini" to "basic" or "full" for different levels of detail.
Monitor System Resources
These commands help you monitor system performance in real-time:
top # Display active processes and system stats
top -o cpu # Sort processes by CPU usage
top -o mem # Sort processes by memory usage
vm_stat 5 # Memory statistics, refreshed every 5 seconds
iostat 5 # Disk I/O statistics, refreshed every 5 seconds
2. File Management and Search Commands
These commands provide powerful ways to manage and find files beyond what's possible in Finder.
Advanced File Search
Find Files by Name or Content
find ~ -name "*.pdf" -mtime -7 # Find PDFs modified in the last 7 days
find ~ -size +100M # Find files larger than 100MB
grep -r "search term" ~/Documents # Search for text in files within Documents
mdfind "kind:pdf date:yesterday" # Use Spotlight to find PDFs from yesterday
Batch File Operations
Rename Multiple Files
# Rename all .JPG files to .jpg in current directory
for file in *.JPG; do mv "$file" "${file%.JPG}.jpg"; done
# Add prefix to all .txt files
for file in *.txt; do mv "$file" "prefix_$file"; done
# Remove spaces from filenames
for file in *\ *; do mv "$file" "${file// /_}"; done

Batch file operations in Terminal can save considerable time compared to manual methods
File Comparison and Manipulation
diff file1.txt file2.txt # Compare two text files
wc -l file.txt # Count lines in a file
head -n 20 file.txt # Show first 20 lines of file
tail -n 20 file.txt # Show last 20 lines of file
tail -f /var/log/system.log # Monitor log file in real-time
3. Network Diagnostics and Monitoring
Terminal provides powerful tools for diagnosing network issues and monitoring network activity.
Network Diagnostics
ping example.com # Test connectivity to a server
traceroute example.com # Trace route to a server
whois example.com # Look up domain registration info
dig example.com # DNS lookup
nslookup example.com # Another DNS lookup tool
Network Monitoring
netstat -an | grep LISTEN # Show listening ports
lsof -i :80 # Show processes using port 80
networksetup -listallhardwareports # List all network interfaces
ifconfig en0 # Show configuration for en0 interface
networkQuality # Run network quality test (macOS 12+)
Wi-Fi Diagnostics
# Get current Wi-Fi info
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I
# Scan available Wi-Fi networks
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s
For convenience, you can create an alias for the airport command:
alias airport='/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport'
# Then use:
airport -I
airport -s
4. Security and Maintenance Commands
These commands help maintain your Mac's health and security.
System Maintenance
sudo periodic daily # Run daily maintenance scripts
sudo periodic weekly # Run weekly maintenance scripts
sudo periodic monthly # Run monthly maintenance scripts
sudo periodic all # Run all maintenance scripts
# Flush DNS cache
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder
# Repair disk permissions (for macOS before 10.13)
sudo diskutil repairPermissions /
Security Checks
# List all loaded kernel extensions
kextstat
# Check for listening services
sudo lsof -i -P | grep LISTEN
# Display current firewall status
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate
# Enable firewall
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on
5. Customizing macOS Hidden Settings
The defaults command allows you to modify many hidden settings in macOS.
Finder Customization
# Show hidden files in Finder
defaults write com.apple.finder AppleShowAllFiles -bool true; killall Finder
# Show file extensions in Finder
defaults write NSGlobalDomain AppleShowAllExtensions -bool true; killall Finder
# Show path bar in Finder
defaults write com.apple.finder ShowPathbar -bool true; killall Finder
# Show status bar in Finder
defaults write com.apple.finder ShowStatusBar -bool true; killall Finder
Dock Customization
# Set Dock animation speed (smaller numbers = faster)
defaults write com.apple.dock autohide-time-modifier -float 0.15; killall Dock
# Remove Dock show/hide delay
defaults write com.apple.dock autohide-delay -float 0; killall Dock
# Change the size of Dock icons
defaults write com.apple.dock tilesize -int 48; killall Dock
Screenshot Customization
# Change screenshot format (options: png, jpg, pdf, tiff)
defaults write com.apple.screencapture type -string "jpg"
# Change screenshot location
defaults write com.apple.screencapture location -string "~/Pictures/Screenshots"
# Disable screenshot shadows
defaults write com.apple.screencapture disable-shadow -bool true
# Apply changes
killall SystemUIServer
Pro Tip
To revert any of these settings to their defaults, replace "true" with "false" or change the value back to its original setting.
6. Advanced Terminal Productivity Tips
These commands and techniques can enhance your Terminal workflow.
Command History and Search
history # Show command history
history | grep "search" # Search command history
!! # Repeat last command
!n # Repeat command number n from history
Ctrl+R # Reverse search through command history
Process Management
ps aux # List all running processes
ps aux | grep "Chrome" # Find specific processes
kill PID # Kill process by ID
killall "App Name" # Kill all processes with that name
Terminal Shortcuts
These keyboard shortcuts can speed up your Terminal workflow:
- Ctrl+A: Move cursor to beginning of line
- Ctrl+E: Move cursor to end of line
- Ctrl+K: Delete from cursor to end of line
- Ctrl+U: Delete from cursor to beginning of line
- Ctrl+W: Delete the word before the cursor
- Option+Click: Position cursor at click location
- Cmd+K: Clear screen (alternative to clear command)
7. Customizing Your Terminal Environment
Make Terminal your own by customizing the shell environment.
Shell Configuration
macOS uses Zsh as the default shell. You can customize it by editing the .zshrc file:
# Open .zshrc in TextEdit
open -e ~/.zshrc
# Or edit directly in Terminal with nano
nano ~/.zshrc
Useful Aliases
Add these aliases to your .zshrc file to create shortcuts for common commands:
# Navigation shortcuts
alias ll='ls -la'
alias desktop='cd ~/Desktop'
alias docs='cd ~/Documents'
# Quick open applications
alias chrome='open -a "Google Chrome"'
alias vscode='open -a "Visual Studio Code"'
# Network utilities
alias myip='curl ipinfo.io/ip'
alias flush='sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder'
# System utilities
alias showfiles='defaults write com.apple.finder AppleShowAllFiles TRUE; killall Finder'
alias hidefiles='defaults write com.apple.finder AppleShowAllFiles FALSE; killall Finder'
Terminal Appearance
You can customize your Terminal's appearance in Terminal > Preferences, but for more advanced customization, consider using Oh My Zsh:
# Install Oh My Zsh
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
# Then edit ~/.zshrc to change themes and plugins

A customized Terminal using Oh My Zsh with syntax highlighting and custom prompts
8. Automating Tasks with Shell Scripts
Shell scripts allow you to automate sequences of commands.
Creating a Basic Shell Script
# Create a new script file
touch ~/scripts/backup.sh
# Make it executable
chmod +x ~/scripts/backup.sh
# Edit the script
nano ~/scripts/backup.sh
Here's a simple backup script example:
#!/bin/zsh
# Simple backup script
# Define source and destination
SOURCE="$HOME/Documents"
DESTINATION="$HOME/Backups/Documents_$(date +%Y%m%d)"
# Create destination directory if it doesn't exist
mkdir -p "$DESTINATION"
# Perform the backup using rsync
rsync -av --progress "$SOURCE/" "$DESTINATION"
echo "Backup completed successfully!"
Scheduling Scripts with Cron
You can schedule scripts to run automatically using cron:
# Edit your crontab
crontab -e
# Add a line to run your script at 2 AM every day
0 2 * * * /Users/yourusername/scripts/backup.sh
9. Powerful One-Liners
These single-line commands perform complex tasks.
Useful One-Liners
# Find and delete .DS_Store files
find . -name ".DS_Store" -delete
# List the 10 largest files in a directory
du -h -d 1 | sort -hr | head -10
# Convert all JPEGs in a folder to PNGs
for i in *.jpg; do sips -s format png "$i" --out "${i%.jpg}.png"; done
# Download a website for offline viewing
wget --mirror --convert-links --adjust-extension --page-requisites --no-parent https://example.com
# Create a ZIP archive of a folder excluding certain files
zip -r archive.zip folder -x "*.DS_Store" -x "*/\.*" -x "*/node_modules/*"
# Show all open ports and the processes using them
sudo lsof -iTCP -sTCP:LISTEN -n -P
10. Homebrew and Command-Line Tools
Homebrew is a package manager for macOS that makes it easy to install command-line tools.
Installing Homebrew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Essential Homebrew Packages
# Install useful command-line tools
brew install git
brew install ffmpeg
brew install youtube-dl
brew install htop
brew install tree
brew install bat # Better cat with syntax highlighting
brew install tldr # Simplified man pages with examples
brew install jq # JSON processor
brew install imagemagick # Image manipulation
# Install GUI applications
brew install --cask firefox
brew install --cask visual-studio-code
brew install --cask spotify
Maintaining Homebrew
# Update Homebrew and packages
brew update && brew upgrade
# Clean up old versions
brew cleanup
# Check for problems
brew doctor
Conclusion
The Terminal provides Mac power users with incredible capabilities beyond what's possible through the graphical interface. By mastering these commands and techniques, you can work more efficiently, automate repetitive tasks, and gain deeper control over your Mac.
Remember that with great power comes great responsibility. Always exercise caution when using Terminal commands, especially those requiring sudo privileges. When in doubt, research commands before using them, and consider creating backups before making significant system changes.
As you become more comfortable with the Terminal, you'll likely develop your own collection of favorite commands, aliases, and scripts tailored to your specific needs. The command line may seem intimidating at first, but the productivity gains are well worth the learning curve.
What are your favorite Terminal commands or scripts? Share them in the comments below to help other Mac power users!
Comments (3)
Leave a Comment
Jason Miller
April 22, 2023 at 3:45 PMGreat article! I've been using Terminal for years but still learned some new tricks. Here's one more I use all the time: "caffeinate" to prevent your Mac from sleeping. Just run "caffeinate" and it will prevent sleep until you hit Ctrl+C, or use "caffeinate -t 3600" to prevent sleep for 3600 seconds (1 hour).
Karen Zhang
April 23, 2023 at 10:20 AMI just started learning Terminal and this is super helpful! Question though: is there any danger in using these commands? I'm worried about messing up my system.
David Chen
April 23, 2023 at 11:05 AM@Karen - That's a great question! Some Terminal commands (especially those that use "sudo") can indeed make significant changes to your system. I'd recommend starting with basic commands like ls, cd, etc. to get comfortable. For more advanced commands, especially those changing system settings, make sure you understand what they do before running them. Consider making a backup before trying new commands that modify system files. And when in doubt, you can always ask for help in forums or communities like Stack Exchange.
Miguel Sanchez
April 24, 2023 at 9:30 AMOh My Zsh completely changed my Terminal experience! I recommend the "agnoster" theme with Powerline fonts, and plugins like git, z, and autosuggestions. Makes working in Terminal so much more efficient and visually pleasing.