The Ultimate Mac Terminal Commands Cheat Sheet: Unleash the Power of Your macOS
Welcome to the definitive guide for mastering the Mac Terminal. For many users, the Terminal application can appear as an intimidating gateway into the inner workings of macOS, a stark contrast to the visually intuitive graphical user interface we’ve grown accustomed to. However, for those willing to delve deeper, the Terminal unlocks a world of power and efficiency, allowing for advanced system management, streamlined workflows, and unparalleled control over your Mac. At MakeUseOf, we believe in empowering our readers with the knowledge to not only use their technology but to truly master it. This comprehensive cheat sheet is meticulously crafted to serve as your ultimate resource, ensuring you can navigate and command your Mac with confidence and precision. We have analyzed the leading resources on this topic and have synthesized their strengths, combined with our deep understanding of macOS and user needs, to bring you a guide that aims to outrank all others in terms of comprehensiveness, clarity, and practical applicability.
This extensive article will not just present a list of commands; it will guide you through their purpose, provide clear examples, and offer insights into how they can be integrated into your daily computing routines. Whether you are a seasoned developer, a dedicated system administrator, an aspiring power user, or simply someone curious about the hidden capabilities of their Mac, this guide is designed to meet your needs. We will explore fundamental navigation, file manipulation, system information retrieval, process management, network diagnostics, and much more. Prepare to transform your interaction with macOS by harnessing the unmatched capabilities of the command line interface.
Getting Started: Launching and Understanding the Terminal
Before we dive into the commands themselves, it’s crucial to understand how to access and interact with the Terminal. The Terminal application is a built-in utility that provides a text-based interface to the operating system. It allows you to execute commands that control various aspects of your Mac’s functionality.
Launching the Terminal Application
Accessing the Terminal is straightforward:
- Using Spotlight Search: Press
Command + Spaceto open Spotlight Search. Type “Terminal” and pressEnter. - Via Finder: Navigate to
Applications > Utilities > Terminal.
Upon launching, you will be presented with a window displaying a command prompt. This prompt typically includes your username, the hostname of your Mac, and your current directory, followed by a $ symbol. For example: yourusername@yourmac:~ $. The ~ symbol represents your home directory.
Understanding the Command Prompt and Basic Syntax
The Terminal operates on a principle of receiving commands and then executing them. Each command generally follows a structure:
command [options] [arguments]
- Command: The executable program or utility you wish to run (e.g.,
ls,cd,pwd). - Options (Flags): These are modifiers that alter the command’s behavior. They usually start with a hyphen (
-) for short options (e.g.,-l) or two hyphens (--) for long options (e.g.,--all). - Arguments: These are the targets or objects that the command acts upon, such as file names, directory paths, or specific parameters.
It is essential to be precise with your typing, as the Terminal is case-sensitive. An incorrect character or spacing can lead to an error message.
Essential Navigation Commands: Moving Around Your File System
Navigating your Mac’s file system is a fundamental skill in the Terminal. These commands allow you to move between directories and see the contents of your current location.
pwd (Print Working Directory)
This command displays the absolute path of your current directory. It is invaluable for understanding precisely where you are within the file system hierarchy.
- Usage:
pwd - Example Output:
/Users/yourusername/Documents
ls (List Directory Contents)
The ls command is used to list files and directories within the current directory or a specified directory. It’s one of the most frequently used commands.
Basic Usage:
lsThis will list the names of files and directories in the current location.
Listing with Details (
-l): The-loption provides a long listing format, showing permissions, owner, group, size, modification date, and file name.ls -lExample Output:
-rw-r--r-- 1 yourusername staff 1234 Jan 15 10:30 mydocument.txt drwxr-xr-x 5 yourusername staff 160 Jan 14 09:00 MyProject- The first character indicates the file type (
-for file,dfor directory). - The subsequent characters represent read (r), write (w), and execute (x) permissions for the owner, group, and others.
- The first character indicates the file type (
Listing All Files, Including Hidden Ones (
-a): Hidden files and directories in macOS (and Unix-like systems) begin with a dot (.). The-aoption reveals them.ls -aCombining Options (
-la): You can combine options for more detailed output.ls -laThis displays all files, including hidden ones, in the long listing format.
cd (Change Directory)
The cd command allows you to change your current working directory.
Moving to a Specific Directory:
cd DocumentsThis moves you into the
Documentsdirectory within your current location.Moving to a Specific Path:
cd /Users/yourusername/DesktopThis moves you directly to the
Desktopdirectory, regardless of your current location.Moving Up One Directory:
cd ..The
..refers to the parent directory.Moving to Your Home Directory:
cdor
cd ~Both commands will take you back to your home directory.
pushd and popd (Directory Stack Management)
These commands are incredibly useful for managing multiple directory locations without having to constantly type cd commands. pushd adds a directory to the top of a stack and changes to it, while popd removes the top directory from the stack and changes to it.
Usage:
pushd /Users/yourusername/Downloads pushd /Users/yourusername/DocumentsNow, if you type
dirs, you’ll see a list of directories you’ve visited in order.Returning to the Previous Directory:
popdThis will take you back to
/Users/yourusername/Downloads.
File and Directory Manipulation: Creating, Copying, Moving, and Deleting
Once you can navigate, the next step is to learn how to manage files and directories.
mkdir (Make Directory)
This command is used to create new directories.
Basic Usage:
mkdir NewFolderThis creates a directory named
NewFolderin your current location.Creating Multiple Directories:
mkdir Folder1 Folder2 Folder3Creating Nested Directories:
mkdir -p Projects/Web/FrontendThe
-poption creates parent directories as needed.
touch (Create Empty File or Update Timestamp)
The touch command is primarily used to create new, empty files. It also updates the access and modification timestamps of an existing file.
Creating a New File:
touch new_file.txtCreating Multiple Files:
touch file1.txt file2.log file3.md
cp (Copy Files and Directories)
The cp command is for copying files and directories.
Copying a File:
cp source_file.txt destination_file.txtThis copies
source_file.txttodestination_file.txt. Ifdestination_file.txtalready exists, it will be overwritten.Copying a File to a Directory:
cp mydocument.txt /Users/yourusername/Documents/This copies
mydocument.txtinto theDocumentsdirectory, keeping its original name.Copying a Directory (
-rfor Recursive): To copy a directory and its contents, you must use the-r(recursive) option.cp -r MyProject BackupProjectsThis copies the
MyProjectdirectory and all its contents into a new directory namedBackupProjects.
mv (Move or Rename Files and Directories)
The mv command serves two primary purposes: moving files/directories from one location to another, and renaming them.
Renaming a File:
mv old_name.txt new_name.txtMoving a File to a Directory:
mv mydocument.txt /Users/yourusername/Documents/Moving and Renaming:
mv mydocument.txt /Users/yourusername/Documents/report.txtMoving a Directory:
mv MyProject /Users/yourusername/Archives/
rm (Remove Files or Directories)
The rm command is used to delete files or directories. Use this command with extreme caution, as deleted files are not moved to the Trash and are generally irrecoverable.
Removing a File:
rm unwanted_file.txtRemoving Multiple Files:
rm file1.txt file2.logRemoving a Directory (
-rfor Recursive): To remove a directory and all its contents, you must use the-roption.rm -r OldProjectForce Removal (
-f): The-f(force) option will remove files without prompting for confirmation, even if they are write-protected. This is particularly dangerous.rm -rf SensitiveDataThis command should be used with the utmost care and understanding.
rmdir (Remove Empty Directories)
A safer alternative to rm -r for directories, rmdir only removes directories that are empty.
- Usage:
rmdir EmptyFolder
Viewing and Editing Files: Exploring Content
Once files exist, you’ll often need to view or edit their contents.
cat (Concatenate and Display File Content)
The cat command is used to display the entire content of a file to the standard output. It can also concatenate multiple files.
Displaying a Single File:
cat mydocument.txtDisplaying Multiple Files:
cat file1.txt file2.txtThis will display the content of
file1.txtfollowed immediately by the content offile2.txt.
less (View File Content Page by Page)
For larger files, less is a superior alternative to cat. It allows you to scroll through the file content page by page, making it much more manageable.
- Usage:
less large_log_file.log- Navigation: Use arrow keys, Page Up, Page Down,
j(down one line),k(up one line). - Search: Press
/followed by your search term, thenEnter. Pressnto find the next occurrence. - Quit: Press
q.
- Navigation: Use arrow keys, Page Up, Page Down,
head and tail (Display Beginning or End of Files)
These commands are useful for quickly inspecting the start or end of a file.
head: Displays the first 10 lines of a file by default.head mydocument.txtYou can specify the number of lines with the
-noption:head -n 5 mydocument.txttail: Displays the last 10 lines of a file by default.tail mydocument.txtYou can specify the number of lines with the
-noption:tail -n 20 mydocument.txtA particularly useful option is
-f(follow), which continuously displays new lines as they are added to a file, ideal for monitoring log files in real-time.tail -f application.log
nano (Simple Text Editor)
nano is a user-friendly command-line text editor. It’s excellent for beginners and for quick edits.
Opening a File:
nano mydocument.txtIf the file doesn’t exist, it will be created upon saving.
Editing: Type your content. Commands are listed at the bottom of the screen, prefixed by
^(Ctrl).- To Save: Press
Ctrl + O. - To Exit: Press
Ctrl + X. You’ll be prompted to save if changes were made.
- To Save: Press
vim (Powerful Text Editor)
vim is a highly powerful and versatile text editor renowned for its efficiency, though it has a steeper learning curve.
Opening a File:
vim config.confModes of Operation:
- Normal Mode: The default mode. Used for navigation and executing commands. Press
Escto return to Normal mode. - Insert Mode: Used for typing text. Press
ito enter Insert mode. - Command-Line Mode: Used for saving, quitting, and advanced operations. Press
:to enter Command-line mode.
- Normal Mode: The default mode. Used for navigation and executing commands. Press
Basic
vimCommands:i: Enter Insert mode.Esc: Return to Normal mode.:w: Save the file (write).:q: Quit the editor.:wq: Save and quit.dd: Delete the current line (in Normal mode).x: Delete the character under the cursor (in Normal mode)./search_term: Search for text (in Command-line mode).
System Information and Management: Knowing Your Mac
The Terminal provides extensive tools for understanding and managing your Mac’s system.
top (Display System Processes)
top provides a real-time view of running processes, their CPU and memory usage, and other system performance metrics.
- Usage:
top- Sorting: Press
Mto sort by memory usage,Pto sort by CPU usage. - Quitting: Press
q.
- Sorting: Press
htop (Interactive Process Viewer)
htop is an enhanced, interactive version of top. It’s not typically installed by default but can be installed via Homebrew (brew install htop). It offers a more user-friendly and visually appealing interface.
ps (Process Status)
ps displays a snapshot of currently running processes.
- Listing All Processes:
ps auxa: Show processes for all users.u: Display in user-oriented format.x: Show processes not attached to a terminal.
kill (Terminate Processes)
The kill command is used to send signals to processes, most commonly to terminate them. You need the Process ID (PID), which can be found using top or ps.
Finding a Process ID:
ps aux | grep "AppName"This will output lines containing “AppName” and their PIDs.
Terminating a Process (Graceful Shutdown):
kill PID_NUMBERThis sends the
TERMsignal (15), asking the process to shut down gracefully.Force Terminating a Process (Immediate Kill):
kill -9 PID_NUMBERThis sends the
KILLsignal (9), which forcibly terminates the process without allowing it to clean up. Use this as a last resort.
df (Disk Free Space)
df reports file system disk space usage.
Basic Usage:
dfThis shows usage in blocks, which can be hard to read.
Human-Readable Format (
-h):df -hThis displays sizes in gigabytes (G), megabytes (M), etc.
du (Disk Usage)
du estimates file space usage.
Usage for Current Directory:
duThis shows the disk usage of subdirectories in the current directory.
Human-Readable Format and Summary (
-sh):du -sh *This shows the total size of each file and directory in the current location in a human-readable format.
uname (System Information)
uname prints system information.
Displaying Kernel Name:
unameOutput:
Darwin(for macOS).Displaying Kernel Version (
-r):uname -rDisplaying All Information (
-a):uname -a
sudo (Execute Command as Superuser)
The sudo command allows a permitted user to execute a command as another user, typically the superuser (root). This is essential for tasks requiring administrative privileges, such as installing software or modifying system files.
- Usage:You will be prompted to enter your user password.
sudo command_to_run
Networking Commands: Diagnosing and Managing Connections
The Terminal is a powerful tool for network troubleshooting and management.
ping (Send ICMP Echo Requests)
ping tests the reachability of a network host and measures the round-trip time for messages.
- Usage:This sends packets to
ping google.comgoogle.comand reports success or failure, along with latency. PressControl + Cto stop.
ifconfig (Network Interface Configuration)
ifconfig is used to configure and display network interface parameters.
- Usage:This will show details about your network interfaces, including your IP address. Look for
ifconfigen0(usually Ethernet or Wi-Fi) and yourinetaddress.
traceroute (Trace Network Path)
traceroute displays the route packets take to a network host. It’s useful for identifying where network delays or failures occur.
- Usage:
traceroute apple.com
curl (Transfer Data from or to a Server)
curl is a command-line tool for transferring data specified with URL syntax. It supports various protocols like HTTP, HTTPS, FTP, etc. It’s excellent for downloading files or testing API endpoints.
Downloading a File:
curl -O https://example.com/somefile.zipThe
-Ooption saves the file with its original name.Viewing a Web Page’s HTML:
curl https://www.example.com
ssh (Secure Shell)
ssh is used to securely connect to a remote server.
- Usage:You will be prompted for the password of the remote user.
ssh username@remote_host_or_ip
File Permissions: Understanding and Modifying Access
File permissions control who can read, write, and execute files and directories.
chmod (Change File Mode Bits)
chmod is used to change the permissions of files and directories. Permissions are often represented by three sets of rwx (read, write, execute) for the owner, group, and others.
Symbolic Method:
u: User (owner)g: Groupo: Othersa: All (u, g, and o)+: Add permission-: Remove permission=: Set permission exactly
Examples:
chmod u+x myscript.sh # Add execute permission for the owner chmod go-w mydocument.txt # Remove write permission for group and others chmod a+r mynotes.txt # Add read permission for everyone chmod ug+rw,o=r config.file # Give owner/group read/write, others only readOctal (Numeric) Method: Each permission (
r,w,x) has a numerical value:r=4,w=2,x=1. Summing these gives the permission for each category (owner, group, others).7:rwx(4+2+1)6:rw(4+2)5:r-x(4+1)4:r--(4)
Examples:
chmod 755 myscript.sh # Owner: rwx, Group: r-x, Others: r-x (Common for executables) chmod 644 mydocument.txt # Owner: rw, Group: r, Others: r (Common for data files)
chown (Change Owner)
chown changes the owner and/or group of files and directories. This command typically requires sudo.
Changing Owner:
sudo chown newowner mydocument.txtChanging Owner and Group:
sudo chown newowner:newgroup mydocument.txtRecursively Change Owner and Group for a Directory:
sudo chown -R newowner:newgroup MyProject/The
-Roption applies the change to the directory and all its contents.
Archiving and Compression: Managing Files Efficiently
These commands are essential for bundling multiple files or reducing file sizes.
tar (Tape Archive Utility)
tar is used to create and extract archive files (often called “tarballs”). It can also compress them using various algorithms.
Creating an Archive:
tar -cvf archive.tar directory_to_archive/c: Create a new archive.v: Verbose (list files as they are processed).f: Use archive file (must be the last option).
Creating a Compressed Archive (gzip):
tar -czvf archive.tar.gz directory_to_archive/z: Compress using gzip.
Creating a Compressed Archive (bzip2):
tar -cjvf archive.tar.bz2 directory_to_archive/j: Compress using bzip2 (often better compression than gzip).
Extracting an Archive:
tar -xvf archive.tarx: Extract files from an archive.
Extracting a Compressed Archive (gzip):
tar -xzvf archive.tar.gzExtracting a Compressed Archive (bzip2):
tar -xjvf archive.tar.bz2
Other Useful Commands and Concepts
man(Manual Pages): This command provides detailed documentation for other commands. If you ever forget how a command works or want to explore its options, useman.man lsPress
qto exit the manual page.Piping (
|): The pipe symbol allows you to send the output of one command as the input to another command. This is fundamental for creating powerful command chains. For example, listing all files and then filtering for those containing “report”:ls -l | grep reportRedirection (
>and>>):>: Redirects output to a file, overwriting the file if it exists.ls -l > file_list.txt>>: Appends output to a file.echo "Another line." >> file_list.txt
history: Displays a list of commands you have previously executed.clear: Clears the Terminal screen, providing a clean workspace.
Conclusion: Embarking on Your Terminal Journey
Mastering the Mac Terminal is a continuous journey, and this cheat sheet provides a robust foundation of essential commands. By practicing these commands regularly and understanding their nuances, you will significantly enhance your efficiency and unlock deeper control over your macOS environment. The Terminal is not just a tool; it’s a gateway to understanding the powerful underpinnings of your operating system. We encourage you to experiment, explore the man pages for further details, and integrate these commands into your daily workflow. At MakeUseOf, our mission is to empower you with the knowledge to make the most of your technology, and we trust this comprehensive guide will serve as your invaluable companion in mastering the Mac Terminal. Happy commanding!