Mac Terminal Commands

May 18, 2023

Introduction

Apple's macOS is a POSIX-compliant UNIX operating system designed to run on Mac computers. The system features access to the command-line interface through the native Terminal app or third-party terminal emulators.

While many Mac terminal commands are similar to Linux commands, macOS also features system-specific syntax designed to help Mac users manage their hardware and software.

This article provides a comprehensive list of Mac terminal commands alongside a downloadable PDF cheat sheet for easy reference.

Mac terminal commands guide.

Prerequisites

  • A system running macOS.
  • Access to the command line/terminal.

Note: Since both macOS and Linux are compatible with UNIX applications, most commands listed in this overview have their Linux equivalents. While the commands produce the same results in both systems, certain functionalities may differ. Follow the links throughout the article to read Linux tutorials for each command.

Basic Commands

Basic commands for the Mac terminal include utilities for obtaining administrative privileges, manipulating the command output, and finding help. Read more about those commands in the sections below.

Run Command as Super User

Use the sudo command to authenticate as an administrator:

sudo [command] [arguments]

Example
Remove a directory the current user does not own:

sudo rm -rf testdir

Forward Command Output

There are two common scenarios for forwarding command output in macOS:

  • Use the | symbol to pipe the command output as an argument to another command:
[command1] | [command2]

Example
Use the wc command to count the number of words in the output:

echo "one two three" | wc -w
  • Prevent the output of the command from showing in the standard output:
[command] > /dev/null

Print in Terminal

Print text to standard output with the echo command:

echo [text]

Example
Print the value of the HOME variable:

echo $HOME

Command History

The system keeps a record of the executed commands. See the list of the commands you previously used by typing:

history

Helpful ways in which you can use the command history include:

  • Limit the number of displayed history entries:
history -[number-of-items]

Example
See the last five entries:

history -5
  • Execute a command by referring to its value in history:
![value]

Example
Execute the entry number 1009:

!1009
  • Execute the last history entry (the previous command):
!!

Get Help

Mac terminal comes with built-in help features. You can access command-line help in two ways:

  • Adding the --help option displays a summary of the command's functionalities:
[command] --help

Example
Read the help summary for the sudo command:

sudo --help
  • A detailed overview of the command:
man [command]

Exit Session

Exit the current terminal session:

exit

File Management

Use the commands listed in the following sections to manipulate the files on your system. The commands cover all the basic file management operations, such as creating, modifying, and organizing the files.

Create Files

Create an empty file:

touch [filename]

Example
Create a file named test.txt:

touch test.txt

Open Files

Open any file on the system:

open [filename]

If the terminal cannot open the file, macOS detects the default application and opens the file in a separate window.

Example
Open an image on your system:

open pnap.png

View Files

Below is the list of the commands and options for viewing files in macOS:

  • The cat command prints the contents of the file to the standard output:
cat [filename]

Example
Output the contents of the /etc/paths file:

cat /etc/paths
  • Show the file's contents one screen at a time using the less command:
less [filename]
  • Print the first ten lines of the file with the head command:
head [filename]
  • Choose the number of lines head prints by adding the -n option:
head -n [number] [filename]

Example
Print the first three lines of the /etc/paths file:

head -n 3 /etc/paths

Edit Files

macOS comes with two preinstalled command-line editors, Nano and Vim. Open the file in a command-line text editor by typing:

[text-editor-command] [filename]

Example
Open the file named test.txt in Nano:

nano test.txt

Append to File

Use the >> symbols to append content to a text file:

echo "[text]" >> [path-to-file]/[filename]

Example
Add the words "This is a test file" to the file test.txt:

echo "This is a test file" >> test.txt

You can also append the contents of an entire file to another file:

cat [filename] >> [path-to-destination-file]/[filename]

Overwrite File

Overwrite the contents of a file from the command line by using the > symbol.

echo "[text]" > [path-to-file]/[filename]

If the file does not exist, the system creates it.

By using cat, you can replace the entire file contents with another file:

cat [filename] > [path-to-file]/[filename]

Copy Files

Use the cp command to copy files in the Mac terminal. The basic syntax for copying a file is:

cp [path-to-file] [destination-path]

Example
Copy test.txt to the testdir directory located in the home directory:

cp test.txt ~/testdir

Other capabilities of the cp command include:

  • Create a copy of a file in the same directory:
cp [filename] [new-filename]
  • Copy the file to another directory and change the filename:
cp [filename] [destination-path]/[new-filename]
  • If a filename contains spaces, surround it with quotation marks:
cp "[spaced filename]" [destination-path]
  • Copy multiple files to the same location:
cp [file1] [file2] [file3] [destination-path]
  • See the warning if completing the operation would overwrite an already existing file:
cp -i [filename] [destination-path]

Move Files

The mv command moves the file to another location. The basic mv syntax is:

mv [path-to-file] [destination-path]

Example
Move the test.txt file to the home directory:

mv test.txt ~

Use mv to perform several more advanced actions, such as:

  • Rename a file:
mv [filename] [new-filename]
  • Move a file and change its name:
mv [filename] [destination-path]/[new-filename]
  • Receive a warning before overwriting a file:
mv -i [filename] [destination-path]
  • Move all the files with the same extension at once:
mv *.[extension] [destination-path]

Example
Move all the YAML files to the testdir directory:

mv *.yaml ~/testdir

Delete Files

Use the rm command to delete files from the system:

  • The basic rm syntax:
rm [filename]
  • Add the -i option to receive a deletion confirmation message:
rm -i [filename]
  • Force remove the file with the -f option:
rm -f [filename]
  • Remove multiple files at the same time:
rm [file1] [file2] [file3]

Directory Management

The sections below present the most common commands for working with directories in a macOS terminal.

Show Working Directory

Display the name of the current working directory with the pwd command:

pwd

Navigate Directories

The cd command helps the directory tree navigation in macOS. The following is the basic syntax for the command:

cd [directory-path]

If the user does not specify the path, cd opens the home directory. Alternatively, to go to the home directory, type:

cd ~

You can also use the command to gain quick access to:

  • The root directory of the drive:
cd /
  • Previously browsed directory:
cd -
  • Parent directory:
cd ..
  • The directory two levels above:
cd ../..

List Directories

View the contents of a directory with the ls command:

ls

Useful ls options include:

  • See all directories and files, including the ones that are hidden:
ls -a
  • View the list of directories and files with more details, including the file size, ownership, and permissions:
ls -l
  • Sort files and directories by size:
ls -S
  • View the list in multiple columns:
ls -C

Note: Combine the options for more views. For example, to see all the files in a detailed list, type:

ls -la

Copy Directories

Use the cp command with the -r option to copy directories:

cp -r [directory] [destination-path]

Example
Copy the testdir directory to the home directory:

cp -r testdir ~

To copy directory contents rather than the directory itself, use the ditto command:

ditto [directory] [destination-path]

Move Directories

The mv command moves the directory to another directory. The syntax is the same as with moving files:

mv [directory] [destination-path]

Delete Directories

Delete directories with the rm command and the -r option:

rm -r [directory]

Add the -f option to force-remove all the files and sub-directories:

rm -rf [directory]

File Size and Disk Space

Mac terminal allows users to access information about file and directory sizes and the available storage space. The sections below list the commands related to storage monitoring.

List Directory and File Usage

The du command outputs the amount of space utilized by files and subdirectories in the current directory:

du

Useful du options include:

  • -s provides an entry for specific files:
du -s [file1] [file2]
  • -h formats the output into a human-readable format:
du -h
  • -k displays memory in kilobytes, -m shows megabytes, and -g shows gigabytes.
du -k

Example
Display memory in megabytes and pipe that output to the sort command to display the directories and files in descending order according to their size:

du -m | sort -nr

Calculate Space

Display the free disk space of the system.

df -h

The -h flag shows the values using the powers of 1024. To change the values to the powers of 1000, use the -H flag:

df -H

Permissions

Managing permissions in the Mac terminal includes viewing and changing access privileges related to specific files and directories and changing the item ownership. The following sections explain permission management in more detail.

Display Permissions

View the permissions related to a specific file by using the -l option and providing the filename as the argument:

ls -l [filename]

Example: View the permissions of test.txt:

ls -l test.txt

To view directory permissions, add the -d option:

ls -ld [directory-path]

If no directory path is specified, the command displays the permissions for the current working directory.

Change Permissions

Change read, write, and execute privileges of a file with the chmod command. The syntax for changing file permissions is:

chmod [number] [filename]

The [number] is a three-digit number in which digits represent user, group, and owner permissions. The number is a sum of all the permissions (read, write, and execute) given to the user, group, and owner.

The numerical values of the permissions are:

  • read has a value of 4.
  • write has a value of 2.
  • execute has a value of 1.
  • no permission has a value of 0.

Example

Change the permissions of the test.txt so that only the user can read, write, and execute it:

chmod 700 test.txt

Use the -R option to change directory permissions:

chmod -R [number] [directory]

Change Ownership

Change which user owns the file by using the following syntax:

chown [username]:[group] [filename]

To change directory ownership, add the -R flag.

chown -R [username]:[group] [directory-path]

Processes

Monitoring processes helps the user get a better picture of resource consumption on the machine and troubleshoot potential issues. Read this section to learn how to list, find, and stop running processes on a Mac machine.

View Processes

List the currently running processes sorted by PID (Process ID) with the ps command:

ps -ax

To see more details about each process, including the CPU and memory consumption, enter the following command:

ps aux

For a detailed process list that updates in real time, use the top command:

top

By default, top refreshes the view every second. Set a custom refresh interval by typing:

top -s [number-of-seconds]

Example
Refresh top data every 10 seconds:

top -s 10

Adjust the view in top to see the data sorted by memory usage:

top -o rsize

To sort the processes by CPU, type:

top -o cpu

Find Processes

Search for a specific process by piping the output of the ps command to grep:

ps -ax | grep [process-name-or-PID]

Quit Processes

Use the kill command to quit a misbehaving process by entering its PID:

kill [PID]

Quit a process by its name with the killall command:

killall [process-name]

Network

Mac terminal supports many networking options, such as viewing and configuring the local network, connecting to remote computers, etc. The sections below explain how to perform the most common network operations.

View Network Information

Test if a remote host is reachable on the network with the ping command:

ping [hostname-or-IP-address]

Use the arp command to view a list of devices on the local network, with their IP and MAC addresses:

arp -a

View the path of the packets from the machine to the destination with the traceroute command:

traceroute [hostname-or-IP-address]

View Network Adapters

Display the connected network adapters with the ifconfig command.

ifconfig

To view a specific adapter, pass its name as an argument to the command:

ifconfig [network-adapter-name]

Download Files

The curl command allows data transfers to and from remote servers. Use curl to download a file to your machine by using the -O option and passing the full URL as an argument:

curl -O [URL]/[filename]

Connect via SSH

Use the following syntax to establish an SSH connection with a remote server:

ssh [username]@[hostname-or-IP-address]

When connecting to a remote host for the first time, you may need to generate an SSH key:

ssh-keygen

After generating the key, copy it to the remote host:

ssh-copy-id -i [path-to-PUB-key] [username]@[hostname-or-IP-address]

Note: You can also use the PuTTY SSH client to establish a connection. Read How to Install PuTTY on Mac for a detailed tutorial.

Environment Variables

Managing application execution parameters with environment variables is an important command-line functionality. Learn how to view and create variables in the following sections.

Display Variables

Display the list of all the variables on the system with the printenv command:

printenv

Use echo to print the value of a specific variable:

echo $[variable]

Export to Path Variable

Add a new binary path to the PATH variable:

export PATH=$PATH:[path-to-executable]

Set Variables

Create a new variable by passing its name and value to the export command:

export [variable-name]=[variable-value]

Note: Variables created in this way will exist only for the duration of the session. To learn how to create permanent variables and learn more about environment variable management in macOS, read How to Set Environment Variables in macOS.

Search

The following are the Mac terminal commands for finding files and content within files:

  • Find a file within a directory:
find [directory] -name "[filename]"

Example

Search for test.txt in the testing directory:

find testing -name "test.txt"
  • Use the wildcard character * to broaden your search.

Example

Look for all the TXT files in the testing directory:

find testing -name "*.txt"
  • Use grep to search for text within a file:
grep "[text]" [filename]
  • Find text in the command output by piping the output to grep:
[command] | grep "[text]"
  • To search for text across the files in a directory, use the following syntax:
grep -rl "[text]" [directory]

Homebrew Commands

Homebrew is the default package manager for macOS. It provides Mac with functionalities usually found in Linux package managers, such as APT, RPM, etc. Below is the list of the most common Homebrew operations.

Manage Formulas

Below are the operations you can perform on Homebrew formulae and casks:

  • Update the formulae:
brew update
  • Upgrade the formulae:
brew upgrade
  • Upgrade a specific formula:
brew upgrade [formula]
  • Prevent a formula from receiving an update:
brew pin [installed-formula]
  • Remove the pin and allow the formula to update:
brew unpin [pinned-formula]
  • Install a formula:
brew install [formula]
  • Remove a formula from the system:
brew uninstall [formula]

View Information

Learn more about the state of your homebrew formulae and casks by using the commands below:

  • Display a list of the formulae currently installed on the system:
brew list --formula
  • View a list of the currently installed casks:
brew list --cask
  • Show dependency packages for a specified formula:
brew deps [formula]
  • Display outdated formulae on the system:
brew outdated --formula
  • List outdated casks:
brew outdated --cask

Manage Homebrew

Troubleshoot potential problems with Homebrew with the following commands:

  • Execute the doctor subcommand:
brew doctor
  • Access the help resources:
brew help
  • Clean the system from outdated packages and stale lock files:
brew cleanup

System

The following is a list of useful terminal commands for maintaining your macOS system:

  • Keep Mac awake:
caffeinate
  • Check for system updates:
softwareupdate -l
  • Apply system updates:
sudo softwareupdate -i -a -R
  • Reset macOS Dock:
killall Dock
  • Reset Launchpad:
defaults write com.apple.dock ResetLaunchPad -bool true; killall Dock
  • Flush DNS cache:
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder
  • Access iCloud documents:
cd ~/Library/Mobile\ Documents/com~apple~CloudDocs/
  • Restart Mac:
sudo shutdown -r now
  • Shut down Mac:
sudo shutdown -h now

Shortcuts

Mac terminal has many useful keyboard shortcuts for managing terminal windows and navigating the terminal. Below is the list of the most helpful shortcuts, divided into categories for easier browsing.

Window and Tab Management

ShortcutDescription
Command - NOpen a new window.
Shift - Command - WClose the window.
Command - TOpen a new tab.
Command - WClose the tab.
Option - Shift - Command - WClose all terminal instances.
Command - +/-Make the text bigger/smaller.
Command - DSplit the window into two panes.
Shift - Command - DClose the split pane.

Command Line Navigation

ShortcutDescription
Control - AMove the insertion point to the beginning.
Control - EMove the insertion point to the end.
Control - UDelete the line.
Control - KDelete text from the active position to the end of the line.
Option - Right ArrowMove forward word by word.
Option - Left ArrowMove backward word by word.

Select and Find in Terminal

ShortcutDescription
Shift - Command - click the file path.Select the entire file path.
Triple-click the line.Select the entire line.
Command - XCut the selection.
Command - CCopy the selection.
Option - Shift - Command - CCopy plain text.
Command - VPaste.
Command - FFind text.
Command - EFind the preselected text.
Command - JJump to the selected text.
Command - ASelect all.

Miscellaneous Shortcuts

ShortcutDescription
Control - Command - FFull-screen mode on/off.
Command - double-click the URL.Open a URL.
Command - PPrint.
Command - KClear screen, except for the current prompt.
Control - Shift - Command - ?Open the man pages.

Mac Terminal Commands Cheat Sheet PDF

We created a handy Mac terminal commands cheat sheet as a one-page reference for all the essential macOS commands. Save the PDF list of macOS commands by clicking the Download the macOS Cheat Sheet button below.

Mac terminal commands cheat sheet.

Conclusion

This Mac terminal guide listed all the important commands for navigating the terminal and performing the basic file, directory, and network management functions.

The guide also provided a PDF cheat sheet with the same commands on one easy-to-navigate page for quicker reference.

Was this article helpful?
YesNo
Marko Aleksic
Marko Aleksić is a Technical Writer at phoenixNAP. His innate curiosity regarding all things IT, combined with over a decade long background in writing, teaching and working in IT-related fields, led him to technical writing, where he has an opportunity to employ his skills and make technology less daunting to everyone.
Next you should read
How to Set Environment Variables in MacOS
January 18, 2021

This tutorial explains how to view, add, and remove temporary and permanent environment variables on macOS.
Read more
How to Install Java on Mac
July 21, 2022

Learn how to install the Java Development Kit (JDK) and the Java Runtime Environment (JRE) on macOS.
Read more
How to Install Pip on Mac
September 28, 2021

Pip is a package management system used for installing and managing Python software packages and libraries...
Read more
How to Install and Get started with Git on Mac
February 4, 2020

Git is a version control system that allows developers to track a project and actively contribute...
Read more