Skip to content
Home » macOS Terminal Essential Commands Guide for Beginners

macOS Terminal Essential Commands Guide for Beginners

macOS Terminal Essential Commands Guide for Beginners

Introduction: Why Learn Terminal Commands?

The Terminal is one of the most powerful tools in macOS, offering direct access to the Unix-based system underneath the beautiful graphical interface. While it might seem intimidating at first, mastering basic Terminal commands can significantly boost your productivity and give you greater control over your Mac.

This comprehensive guide will take you from complete beginner to confident Terminal user, covering essential commands, practical examples, and best practices for macOS.

1. Getting Started with Terminal

Opening Terminal

There are several ways to open Terminal on macOS:

  • Spotlight Search: Press Cmd + Space, type “Terminal”, and press Enter
  • Applications: Go to Applications → Utilities → Terminal
  • Launchpad: Open Launchpad and search for Terminal

Understanding the Command Prompt

When you open Terminal, you’ll see a prompt that looks something like this:

“`
MacBook-Pro:~ username$
“`

This prompt contains important information:

  • MacBook-Pro: Your computer’s name
  • ~: Current directory (~ represents your home directory)
  • username: Your username
  • $: Indicates you’re running as a regular user (# would indicate root/admin)

Basic Command Structure

Terminal commands follow this general structure:

“`
command [options] [arguments]
“`

For example:

“`
ls -la /Users
“`

Where:

  • ls is the command
  • -la are options (flags)
  • /Users is the argument (target directory)

2. File and Directory Operations

Navigation Commands

pwd – Print Working Directory

Shows your current location in the file system:

“`
pwd
“`

ls – List Directory Contents

Lists files and directories in the current location:

“`
# Basic listing
ls

# Detailed listing with permissions, sizes, and dates
ls -l

# Include hidden files (those starting with .)
ls -a

# Combine options for detailed listing including hidden files
ls -la

# List with human-readable file sizes
ls -lh

# Sort by modification time (newest first)
ls -lt
“`

cd – Change Directory

Navigate to different directories:

“`
# Go to home directory
cd
cd ~

# Go to root directory
cd /

# Go to a specific directory
cd /Applications

# Go up one directory level
cd ..

# Go up two directory levels
cd ../..

# Go to previous directory
cd –

# Navigate to a subdirectory
cd Documents/Projects
“`

File and Directory Management

mkdir – Create Directories

“`
# Create a single directory
mkdir NewFolder

# Create multiple directories
mkdir Folder1 Folder2 Folder3

# Create nested directories (create parent directories if needed)
mkdir -p Projects/Web/HTML

# Create directory with specific permissions
mkdir -m 755 SecureFolder
“`

touch – Create Files

“`
# Create a new empty file
touch newfile.txt

# Create multiple files
touch file1.txt file2.txt file3.txt

# Update modification time of existing file
touch existing_file.txt
“`

cp – Copy Files and Directories

“`
# Copy a file
cp source.txt destination.txt

# Copy a file to a directory
cp file.txt /path/to/directory/

# Copy multiple files to a directory
cp file1.txt file2.txt /path/to/directory/

# Copy a directory and its contents recursively
cp -r SourceFolder DestinationFolder

# Copy with verbose output (shows what’s being copied)
cp -v source.txt destination.txt

# Copy and preserve attributes (timestamps, permissions)
cp -p source.txt destination.txt
“`

mv – Move and Rename Files

“`
# Rename a file
mv oldname.txt newname.txt

# Move a file to a directory
mv file.txt /path/to/directory/

# Move multiple files to a directory
mv file1.txt file2.txt /path/to/directory/

# Move and rename simultaneously
mv old_location/file.txt new_location/newname.txt

# Move a directory
mv OldFolder NewLocation/
“`

rm – Remove Files and Directories

“`
# Remove a file
rm filename.txt

# Remove multiple files
rm file1.txt file2.txt file3.txt

# Remove files with confirmation prompt
rm -i filename.txt

# Remove a directory and its contents recursively
rm -r DirectoryName

# Force remove without confirmation (be careful!)
rm -f filename.txt

# Remove directory recursively and forcefully
rm -rf DirectoryName

# Remove all .tmp files in current directory
rm *.tmp
“`

3. Text Processing and File Content

Viewing File Contents

cat – Display File Contents

“`
# Display entire file content
cat filename.txt

# Display multiple files
cat file1.txt file2.txt

# Display with line numbers
cat -n filename.txt

# Display non-printing characters
cat -A filename.txt
“`

less and more – Page Through Files

“`
# View file with pagination (recommended)
less filename.txt

# Older paging command
more filename.txt
“`

In less, you can use:

  • Space: Next page
  • b: Previous page
  • /text: Search for “text”
  • q: Quit

head and tail – Display Parts of Files

“`
# Show first 10 lines of a file
head filename.txt

# Show first 20 lines
head -n 20 filename.txt

# Show last 10 lines of a file
tail filename.txt

# Show last 20 lines
tail -n 20 filename.txt

# Follow file changes in real-time (useful for logs)
tail -f logfile.txt
“`

Text Search and Manipulation

grep – Search Text Patterns

“`
# Search for text in a file
grep “search_term” filename.txt

# Case-insensitive search
grep -i “search_term” filename.txt

# Search in multiple files
grep “search_term” *.txt

# Search recursively in directories
grep -r “search_term” /path/to/directory

# Show line numbers with matches
grep -n “search_term” filename.txt

# Show only filenames containing the pattern
grep -l “search_term” *.txt

# Count number of matches
grep -c “search_term” filename.txt

# Invert match (show lines that don’t contain pattern)
grep -v “search_term” filename.txt
“`

find – Locate Files and Directories

“`
# Find files by name
find /path/to/search -name “filename.txt”

# Find files with wildcard pattern
find . -name “*.txt”

# Find directories
find /path/to/search -type d -name “dirname”

# Find files modified in last 7 days
find . -mtime -7

# Find files larger than 100MB
find . -size +100M

# Find files and execute command on them
find . -name “*.log” -exec rm {} \;

# Find files with specific permissions
find . -perm 755
“`

4. System Information and Monitoring

System Information

System Overview Commands

“`
# Display system information
uname -a

# Show macOS version
sw_vers

# Display current date and time
date

# Show system uptime
uptime

# Display current user
whoami

# Show all logged-in users
who

# Display user and group information
id
“`

Process and Resource Monitoring

ps – Process Status

“`
# Show your running processes
ps

# Show all processes with detailed information
ps aux

# Show processes for a specific user
ps -u username

# Show process tree
ps -ef

# Find specific processes
ps aux | grep “process_name”
“`

top – Real-time Process Monitor

“`
# Display real-time process information
top

# Sort by CPU usage (default)
top -o cpu

# Sort by memory usage
top -o mem

# Show only processes for current user
top -U $USER
“`

In top, you can use:

  • q: Quit
  • k: Kill a process (enter PID)
  • s: Change update interval

Activity and Resource Usage

“`
# Show disk usage of current directory
du -sh

# Show disk usage of all subdirectories
du -h

# Display filesystem disk space usage
df -h

# Show memory usage
vm_stat

# Display running processes with resource usage
htop # (if installed via Homebrew)
“`

5. Network Commands

Network Connectivity

ping – Test Network Connectivity

“`
# Ping a website
ping google.com

# Ping with specific count
ping -c 5 google.com

# Ping with specific interval (in seconds)
ping -i 2 google.com
“`

Network Information

“`
# Show network configuration
ifconfig

# Show all network interfaces
networksetup -listallhardwareports

# Show current IP address
curl ifconfig.me

# Show DNS information
nslookup google.com

# Trace route to destination
traceroute google.com

# Show network connections
netstat -an

# Show listening ports
lsof -i
“`

Download and Transfer

curl – Transfer Data

“`
# Download a file
curl -O http://example.com/file.zip

# Download and save with specific name
curl -o myfile.zip http://example.com/file.zip

# Display HTTP headers
curl -I http://example.com

# Follow redirects
curl -L http://example.com

# Download with progress bar
curl -# -O http://example.com/largefile.zip
“`

wget – Web Download (if installed)

“`
# Download a file
wget http://example.com/file.zip

# Download recursively
wget -r http://example.com/

# Continue partial download
wget -c http://example.com/largefile.zip
“`

6. Permissions and User Management

File Permissions

chmod – Change File Permissions

“`
# Make file executable
chmod +x script.sh

# Remove execute permission
chmod -x script.sh

# Set specific permissions (owner: read/write/execute, group: read/execute, others: read)
chmod 754 filename

# Set permissions recursively
chmod -R 755 directory/

# Common permission combinations:
chmod 644 file.txt # rw-r–r– (typical file)
chmod 755 script.sh # rwxr-xr-x (executable script)
chmod 700 private/ # rwx—— (private directory)
“`

chown – Change Ownership

“`
# Change owner of a file
sudo chown newowner filename

# Change owner and group
sudo chown newowner:newgroup filename

# Change ownership recursively
sudo chown -R newowner:newgroup directory/
“`

User and Group Information

“`
# Show current user
whoami

# Show user information
id

# List all users
dscl . list /Users

# Show group membership
groups username

# Switch to another user
su – username
“`

7. Process Management

Managing Running Processes

Background and Foreground Jobs

“`
# Run command in background
command &

# List background jobs
jobs

# Bring job to foreground
fg %1

# Send job to background
bg %1

# Suspend current process (Ctrl+Z alternative)
kill -STOP PID
“`

Killing Processes

“`
# Kill process by PID
kill 1234

# Force kill process
kill -9 1234

# Kill process by name
killall ProcessName

# Kill all processes matching pattern
pkill -f “pattern”

# Interactive process killer
top (then press ‘k’ and enter PID)
“`

8. Environment Variables and Shell Configuration

Environment Variables

Viewing and Setting Variables

“`
# Show all environment variables
env

# Show specific variable
echo $PATH
echo $HOME

# Set temporary variable
export MYVAR=”value”

# Add to PATH
export PATH=”$PATH:/new/path”

# Show shell type
echo $SHELL
“`

Shell Configuration

Profile Files

macOS uses zsh by default (since Catalina). Common configuration files:

“`
# Edit zsh configuration
nano ~/.zshrc

# Edit bash configuration (if using bash)
nano ~/.bash_profile

# Reload configuration
source ~/.zshrc
“`

Aliases

“`
# Create temporary alias
alias ll=’ls -la’

# Add permanent alias to ~/.zshrc
echo “alias ll=’ls -la'” >> ~/.zshrc

# Show all aliases
alias

# Remove alias
unalias ll
“`

9. Useful Keyboard Shortcuts

Navigation Shortcuts

  • Ctrl + A: Move to beginning of line
  • Ctrl + E: Move to end of line
  • Ctrl + U: Delete from cursor to beginning of line
  • Ctrl + K: Delete from cursor to end of line
  • Ctrl + L: Clear screen
  • Ctrl + R: Search command history
  • Ctrl + C: Cancel current command
  • Ctrl + Z: Suspend current process

History Management

“`
# Show command history
history

# Run previous command
!!

# Run specific command from history
!n # where n is the line number

# Search history
history | grep “search_term”

# Clear history
history -c
“`

10. Advanced Tips and Tricks

Command Chaining and Redirection

Pipes and Redirection

“`
# Pipe output to another command
ls -la | grep “txt”

# Redirect output to file
ls -la > output.txt

# Append output to file
ls -la >> output.txt

# Redirect both stdout and stderr
command > output.txt 2>&1

# Chain commands with AND (second runs only if first succeeds)
mkdir test && cd test

# Chain commands with OR (second runs only if first fails)
cd nonexistent || echo “Directory not found”
“`

Wildcards and Globbing

“`
# Match any characters
ls *.txt

# Match single character
ls file?.txt

# Match character range
ls file[1-5].txt

# Match specific characters
ls file[abc].txt

# Brace expansion
echo {1..10}
mkdir {dir1,dir2,dir3}
“`

Command Substitution

“`
# Use command output as argument
echo “Today is $(date)”

# Store command output in variable
current_dir=$(pwd)

# Use in file operations
cp file.txt backup_$(date +%Y%m%d).txt
“`

11. Package Management Integration

Using Homebrew Commands

If you have Homebrew installed, you can enhance Terminal with additional tools:

“`
# Install useful command-line tools
brew install tree # Display directory structure
brew install htop # Better process monitor
brew install wget # Web downloader
brew install jq # JSON processor
brew install bat # Better cat with syntax highlighting

# Using installed tools
tree # Show directory tree
htop # Launch enhanced process monitor
bat filename.txt # Display file with syntax highlighting
“`

12. Troubleshooting and Common Issues

Permission Issues

“`
# Fix common permission problems
sudo chown -R $(whoami) /usr/local/

# Reset permissions on home directory
sudo chown -R $(whoami):staff ~/

# Fix permission denied errors
chmod +x script.sh
“`

Path Issues

“`
# Check if command exists
which command_name

# Show command location
whereis command_name

# Add directory to PATH temporarily
export PATH=”/new/path:$PATH”

# Make PATH change permanent (add to ~/.zshrc)
echo ‘export PATH=”/new/path:$PATH”‘ >> ~/.zshrc
“`

Common Error Solutions

Command Not Found

“`
# Install missing command via Homebrew
brew install command_name

# Check if command is aliased
alias command_name

# Update PATH if needed
export PATH=”$PATH:/path/to/command”
“`

File System Issues

“`
# Check disk space
df -h

# Find large files
find / -size +100M 2>/dev/null

# Clear system caches (be careful)
sudo purge
“`

13. Security Best Practices

Safe Command Usage

  • Always double-check destructive commands like rm -rf
  • Use tab completion to avoid typos in file paths
  • Test commands on non-critical files first
  • Be cautious with sudo – only use when necessary
  • Verify file paths before executing commands

Backup and Recovery

“`
# Create backup before major changes
cp -r important_directory backup_$(date +%Y%m%d)

# Use Time Machine via command line
tmutil startbackup

# Verify critical files exist
test -f important_file.txt && echo “File exists” || echo “File missing”
“`

14. Command Reference Quick Sheet

Navigation

Command Description Example
pwd Show current directory pwd
ls List directory contents ls -la
cd Change directory cd Documents

File Operations

Command Description Example
mkdir Create directory mkdir NewFolder
touch Create file touch file.txt
cp Copy files/directories cp file.txt backup/
mv Move/rename mv old.txt new.txt
rm Remove files/directories rm file.txt

Text Processing

Command Description Example
cat Display file content cat file.txt
less Page through file less file.txt
grep Search text grep “pattern” file.txt
find Locate files find . -name “*.txt”

System Monitoring

Command Description Example
ps Show processes ps aux
top Real-time processes top
df Disk space usage df -h
du Directory size du -sh

15. Next Steps and Advanced Learning

Recommended Learning Path

  1. Practice Daily: Use Terminal for basic file operations
  2. Learn Text Editors: Master nano, vim, or emacs
  3. Explore Scripting: Write simple shell scripts
  4. Study Regular Expressions: Enhance grep and sed usage
  5. Learn Advanced Tools: awk, sed, cut, sort, uniq

Useful Resources

  • Man Pages: Use man command_name for detailed documentation
  • Built-in Help: Most commands support --help or -h flags
  • Online Communities: Stack Overflow, Reddit r/commandline
  • Books: “Learning the Unix Command Line” and “Unix Power Tools”

Building Your Skills

“`
# Practice exercise: Create a project structure
mkdir -p Projects/{Web/{HTML,CSS,JS},Mobile/{iOS,Android},Scripts}
tree Projects

# Practice exercise: Find and organize files
find ~/Downloads -name “*.pdf” -exec cp {} ~/Documents/PDFs/ \;

# Practice exercise: System maintenance
du -sh /Applications/* | sort -hr | head -10
“`

Conclusion

Mastering the Terminal is a journey that pays dividends in productivity and system understanding. These essential commands form the foundation of efficient macOS command-line usage. Remember that practice makes perfect – start with simple commands and gradually work your way up to more complex operations.

The key to success is consistent practice and gradual exploration. Don’t try to memorize everything at once; instead, focus on the commands you use most frequently and build from there. Keep this guide handy for reference, and don’t hesitate to use the built-in help systems (man pages and --help flags) when you need more detailed information about specific commands.

As you become more comfortable with these basics, you’ll find yourself naturally gravitating toward more advanced topics like shell scripting, regular expressions, and system automation. The Terminal will transform from an intimidating black screen into a powerful ally in your daily computing tasks.


Happy commanding! Remember: with great power comes great responsibility – always double-check destructive commands before executing them.

Leave a Reply

Your email address will not be published. Required fields are marked *