Skip to content

zafar1162014/mac-terminal-cheatsheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

Mac Terminal Cheat Sheet

GitHub Repo macOS Shell

Beautiful, practical, and copy-ready commands for daily macOS terminal work.
Beginner to advanced flow with direct section links.

Created by Muhammad Zafar Ul Haq


Tip

On GitHub, every code block has a copy button in the top-right corner. Use those blocks directly to copy commands.

Quick Access


Repository


Getting Started Guide

Terminal Basics

  • Prompt $ means terminal is ready for your command.
  • ~ means your home folder, usually /Users/your-name.

Command Types

  1. Single command
date  # show current local date and time
  1. Command with extra argument
echo "hello"  # print text to terminal output
  1. Command with option and argument
date -u      # show current time in UTC
cal 01 2018  # show calendar for January 2018
  1. Command that prints in multiple lines
echo "message
in two lines"  # print a multi-line message

First Practice Flow (Copy Pack)

# 1) Check current location
pwd

# 2) Go to Desktop
cd ~/Desktop

# 3) Create and enter practice folder
mkdir my-terminal-practice
cd my-terminal-practice

# 4) Create folder and file
mkdir notes
touch notes/today.txt

# 5) Write and read content
echo "My first terminal note" > notes/today.txt
cat notes/today.txt

# 6) Copy and rename (same folder)
cp notes/today.txt notes/today-copy.txt   # cp: make a second copy of the file
mv notes/today-copy.txt notes/backup.txt  # mv: rename that copied file to backup.txt

# 7) Move file to another folder
mkdir backup
mv notes/backup.txt backup/               # mv: move file from notes folder to backup folder

# 8) Show detailed list
ls -lah notes
ls -lah backup

# 9) Search in file
grep -i "first" notes/today.txt

# 10) Clean up
rm backup/backup.txt
rm -r backup
rm -r notes
cd ..
rmdir my-terminal-practice

Quick explanation:

  • cp source destination: copies a file and keeps the original.
  • mv source destination: moves a file to another folder, or renames it if destination is a new file name in the same folder.

Back to top


Essential Commands

whoami  # print current logged-in user

date     # show local date and time
date -u  # show date and time in UTC

cal         # show current month calendar
cal 01 2018 # show specific month and year

echo "message" # print text
echo $USER      # print current username from environment
echo $HOME      # print user home directory path

say "message" # speak text using macOS voice
man ls         # open manual page for ls

clear  # clear visible terminal screen
reset  # reset terminal display and settings

top   # monitor running processes live (press q to quit)
exit  # exit the current shell session

killall "App Name" # terminate all processes by app name

Back to top


Keyboard Shortcuts

Shortcut Action
Tab Auto-complete file and folder names
Ctrl + A Move cursor to start of line
Ctrl + E Move cursor to end of line
Ctrl + U Cut from cursor to line start
Ctrl + Q Resume terminal output flow control
Ctrl + K Cut from cursor to line end
Ctrl + W Cut one word backward
Ctrl + L Clear screen view (keeps history)
Cmd + K Clear terminal output in Terminal app
Cmd + Shift + Left Arrow Select text to line start in many terminals/editors
Ctrl + C Stop running command
Alt + Left/Right Move one word left/right
Ctrl + D Exit current shell
Ctrl + R Search command history

Back to top


Navigation

.   # current directory
..  # parent directory

cd ..    # move up one directory
cd ../.. # move up two directories

cd        # go to home directory
cd ~      # go to home directory explicitly
cd /      # go to filesystem root
cd folder # enter a specific folder
cd -      # return to previous directory

pwd    # print current full directory path
open . # open current directory in Finder

Back to top


List Files

ls         # list files and folders
ls -l      # long listing format with details
ls -a      # include hidden entries
ls -A      # include hidden entries except . and ..
ls -t      # sort by most recently modified
ls -S      # sort by file size (largest first)
ls -F      # show type markers (/, *, etc.)
ls -lh     # long listing with human-readable sizes
ls -althFS # combined useful flags
ls folder  # list contents of a specific folder

ls -l Format

drwxr-xr-x 5 cc eng 4096 Jun 24 16:51 action
-rw-r--r-- 1 cc eng    0 Jun 24 16:51 genres.txt
  • Column 1: permissions
  • Column 2: link count
  • Column 3: owner
  • Column 4: group
  • Column 5: size
  • Column 6: last modified date/time
  • Column 7: file or folder name

Back to top


File Management

touch file.txt   # create empty file or update modified timestamp
open file.txt    # open file with default macOS application
nano file.txt    # edit file in nano terminal editor
nano -m file.txt # edit in nano with mouse support
pico file.txt    # edit file in pico editor
vim file.txt     # edit file in Vim

# Vim quick keys
:q  # quit Vim without saving changes
:wq # write changes and quit Vim

rm file.txt    # remove a file
rm -i file.txt # remove with confirmation prompt
rm -f file.txt # force remove without prompt
rm -rf dir     # remove directory recursively and forcefully
rm folder/*    # remove all files inside folder

cp file1.txt file2.txt # copy file1 into file2
cp file.txt dir/       # copy file into directory
cp -rv source/. dest/  # recursively copy source contents into destination

mv file.txt dir/    # move file into directory
mv old.txt new.txt  # rename file

*.txt      # pattern matching all .txt files
*.*        # pattern matching names containing a dot
letters*.* # pattern matching files starting with "letters"

Back to top


Directory Management

mkdir dir          # create a new directory
mkdir dir && cd dir # create a directory and enter it
mkdir -p a/b/c     # create nested directories in one command
rmdir dir          # remove an empty directory

Back to top


View and Edit Content

cat file.txt               # print file contents
cat -n file.txt            # print file with line numbers
cat file1.txt > file2.txt  # overwrite file2 with file1 content
cat file1.txt >> file2.txt # append file1 content to file2

echo 'message'             # print message text
echo "message" > file.txt  # write message by overwriting file
echo "more text" >> file.txt # append message at file end

more file.txt # view file page-by-page from start
less file.txt # interactive file viewer with scroll/search
sort file.txt # sort lines alphabetically
file file.txt # detect file type information
file *.txt    # show type information for all txt files

pbcopy < file.txt      # copy file contents to macOS clipboard
pbpaste                # print clipboard contents
pbpaste > pasted.txt   # save clipboard contents to file

Back to top


Pipes and Redirection

command1 | command2 # send output of command1 into command2

tail -n 20 file.txt                  # show last 20 lines of file
command1 | tail -n 3                 # show last 3 lines from command output
command1 | tail -n 3 | less          # open last 3 lines in less viewer
command1 | tail -n 3 | sort > out.txt # sort last lines and save to file

command > file.txt  # write output to file (overwrite)
command >> file.txt # write output to file (append)
command < input.txt # read command input from file

Back to top


Search

find .                  # find all files and folders from current directory
find dir -name "*.txt" # find txt files by name pattern
find dir -type f        # find files only
find dir -type d        # find directories only

mdfind "invoice"                     # Spotlight search by metadata/content
mdfind -onlyin ~/Desktop -name report # Spotlight name search inside folder

grep "pattern" file.txt    # print lines matching pattern
grep -i "pattern" file.txt # case-insensitive match
grep -r "pattern" dir      # recursive search in directory
grep -v "pattern" file.txt # print lines that do NOT match

Back to top


History

history    # show command history
history 20 # show last 20 history entries

# shortcut
Ctrl + R

!git   # run last command that starts with git
!git:p # print last command starting with git without running
!!     # run previous command
!!:p   # print previous command without running

Back to top


Command Chaining

commandA ; commandB  # run commandB regardless of commandA result
commandA && commandB # run commandB only if commandA succeeds
commandA || commandB # run commandB only if commandA fails
commandA &           # run commandA in background

Back to top


Ownership and Permissions

sudo command        # run command as superuser
sudo touch file.txt # create file with root privileges
sudo bash           # open root shell session

sudo chown newuser file.txt   # change file owner
sudo chgrp newgroup file.txt  # change file group
sudo chown -R newuser folder  # recursively change owner
sudo chgrp -R newgroup folder # recursively change group

chmod u=rwx file.sh # set owner permissions to read/write/execute
chmod o=rwx file.sh # set others permissions to read/write/execute
chmod +x file.sh    # add executable permission
chmod -x file.sh    # remove executable permission

Back to top


Help Commands

command -h     # show short help for command
command --help # show full help output for command
help           # show shell built-in help
man command    # open manual page for command
whatis command # show one-line command description
apropos keyword # search commands related to keyword

Back to top


Variables and Shell Basics

Variables

myvar=123      # create variable and assign value
echo $myvar    # print variable value
unset myvar    # remove variable
myvar=$(date)  # assign command output to variable

Environment Variables

echo $USER # show current username
echo $HOME # show home directory path
echo $PATH # show executable search paths

Input from User

read myvar                    # read user input into variable
read -p "Enter value: " myvar # show prompt and read input
read -s mysecret              # read secret input without echo
echo $myvar                   # print entered value

Strings

echo "this is a simple string"    # print plain string
echo "this variable is $myvar"    # print string with variable interpolation

Run Scripts

./script.sh        # run script in current directory
/path/to/script.sh # run script using full path
which ls           # show executable location for command

Back to top


Process Commands

ps aux                 # list all running processes with details
top                    # monitor processes in real time
kill <pid>             # terminate process by PID
kill -9 <pid>          # force kill process by PID
killall "Google Chrome" # terminate process by name

Back to top


Git Quick Guide

Clone and Branch

git clone <url>                   # clone remote repository
git checkout -b <new-branch>      # create and switch to new branch
git push -u origin <new-branch>   # push branch and set upstream tracking
git checkout <branch>             # switch to existing branch
git push origin <branch>          # push branch updates to remote

Delete Branches

git branch -d <branchname>    # delete local branch
git push origin :<branchname> # delete remote branch

New Repo Setup

cd project              # enter project directory
git init                # initialize git repository
git add .               # stage all current changes
git commit              # create commit with staged changes
git rm --cached <file>  # untrack file but keep it locally

Merge Flow

git branch                      # list local branches
git checkout -b feature-branch  # create and switch to feature branch
# make changes
git commit -a                   # commit tracked file changes
git checkout master             # switch to master branch
git merge feature-branch        # merge feature branch into current branch

Inspect and Compare

gitk            # open visual commit history tool
git log         # show commit history
git log -p      # show history with patch diffs
git show HEAD   # show latest commit details

git diff origin..master # compare origin and master changes
git diff --stat HEAD    # show summary of unstaged changes

Patches

git format-patch HEAD^               # create patch file from latest commit
git apply < ../p/0001-example.patch  # apply patch from file

Back to top


Advanced Git Workflows

Rename Branch

git branch -m <oldname> <newname> # rename a specific branch
git branch -m <newname>           # rename current branch

Upstream Sync

git remote -v                                # list configured remotes
git remote add upstream <upstream-github-url> # add upstream remote
git fetch upstream                           # fetch refs from upstream
git checkout development                     # switch to development branch
git merge upstream/development               # merge upstream updates locally

Delete and Cleanup

git branch -d <branchname>    # delete local branch
git push origin :<branchname> # delete remote branch
git remote prune origin       # remove stale remote-tracking branches

Referring To Revisions

git log v1.0.0                # show history up to tag v1.0.0
git log master                # show history of master branch
git show master^              # show parent of master tip
git show master~2             # show grandparent of master tip
git show master~3             # show third ancestor of master tip
git show <full-or-short-hash> # show specific commit by hash
git tag v1.0.0                # create tag at current commit
git tag interesting <revision> # tag a specific revision

Docs Publish (Subtree)

git subtree push --prefix docs origin gh-pages # publish docs folder to gh-pages

Back to top


Sublime As Git Editor

cd ~  # go to home directory
mkdir -p bin  # create local bin directory if missing
ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" ~/bin/subl # add Sublime binary symlink
git config --global core.editor "subl -n -w" # set Sublime as global Git editor

If symlink path is missing on your machine:

sudo rm -f /usr/local/bin/subl # remove broken Sublime symlink
sudo ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" /usr/local/bin/subl # recreate system symlink

Back to top


Safety Checklist

# dangerous command (never run)
rm -rf / # deletes the root filesystem recursively

# before deleting anything, verify location
pwd # print current directory before destructive command

# overwrite vs append
command > file  # overwrite file with command output
command >> file # append command output to file
  • Double-check folder path before rm.
  • Prefer rm -i while learning.
  • Use history and !!:p to preview previous commands.

Back to top


Star This Project

If this helped you, please star the repository:

Made with care by Muhammad Zafar Ul Haq

About

A beautifully organized macOS terminal cheat sheet with practical, copy-friendly commands for beginners and advanced users.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors