Unix Commands Cheat Sheet: All the Commands You Need

Unix Commands Cheat Sheet

To make full use of Unix operating systems such as macOS’s Darwin and Linux’s GNU, you need to learn how to operate Unix from the command line. Committing Unix commands and their usage to memory can be a burden. It’s also hard to tell from the official documentation which commands are important and which less so.

This Unix commands cheat sheet aims to help you pick up and brush up high-priority Unix command-line operations easily. It covers essential commands, the in-built text editor vi, and basic shell scripting. A shell script is a computer program designed to run in Unix command-line terminals, and it’s a key building block of programming in Unix.

Download this Unix command cheat sheet here. If you’re ready, let’s dive in below.

Unix Commands Cheat Sheet Search

Search our Unix Commands cheat sheet to find the right cheat for the term you're looking for. Simply enter the term in the search bar and you'll receive the matching cheats available.

Essential Commands

With these commands, you can obtain critical information about your Unix machine and perform key operations.

System Information

These provide information about your Unix machine.

unameShow the Unix system information.
uname -aDetailed Unix system information
uname -rKernel release information, such as kernel version
uptimeShow how long the system is running and load information.
whoDisplay who is logged in.
wDisplay what users are online and what they are doing.
usersList current users.
whoamiDisplay what user you are logged in as.
suSuperuser; use this before a command that requires root access e.g. su shutdown
calShow calendar where the current date is highlighted.
dateShow the current date and time of the machine.
haltStop the system immediately.
shutdownShut down the system.
rebootRestart the system.
last rebootShow reboot history.
man COMMANDShows the manual for a given COMMAND. To exit the manual, press “q”.

Input/Output Redirection

These are helpful for logging program output and error messages.

echo TEXTDisplay a line of TEXT or the contents of a variable.
echo -e TEXTAlso interprets escape characters in TEXT, e.g. \n → new line, \b → backslash, \t → tab.
echo -n TEXTOmits trailing newline of TEXT.
cmd1 | cmd2| is the pipe character; feeds the output of the command cmd1 and sends it to the command cmd2, e.g. ps aux | grep python3.
cmd > fileOutput of cmd is redirected to file. Overwrites pre-existing content of file.
cmd > /dev/nullSuppress the output of cmd.
cmd >> fileOutput of cmd is appended to file.
cmd < fileInput of cmd is read from file.
cmd << delimInput of cmd is read from the standard input with the delimiter character delim to tell the system where to terminate the input. Example for counting the number of lines of ad-hoc input:
wc -l << EOF
> I like
> apples
> and
> oranges.

Hence there are only 4 lines in the standard input delimited by EOF.

File Management

In the following commands: X may refer to a single file, a string containing a wildcard symbol referring to a set of multiple files e.g. file*.txt, or the stream output of a piped command (in which case the syntax would be X | command instead of command X); Y is a single directory; A and B are path strings of files/directories.

*Wildcard symbol for variable length, e.g. *.txt refers to all files with the TXT extension.
?Wildcard symbol referring to a single character, e.g. Doc?.docx can refer to Doc1.docx, DocA.docx, etc.
lsList the names of files and subfolders in the current directory. Options include -l, -a, -t which may be combined e.g. -alt.
ls -lAlso show details of each item displayed, such as user permissions and the time/date when the item was last modified.
ls -aAlso display hidden files/folders. May be combined with ls -l to form ls -al.
ls -tSort the files/folders according to the last modified time/date, starting with the most recently modified item.
ls X List the files 
cd YChange directory to Y. Special instances of Y:
.  — current directory
.. — parent directory
cdTo the $HOME directory
cd ..Up one level to enclosing folder / parent directory
cd /etcTo the /etc directory
cmp A BCompare two files A and B for sameness. No output if A and B are identical, outputs character and line number otherwise.
diff A BCompare two files A and B for differences. Outputs the difference.
pwdDisplay the path of the current working directory.
mkdir XMake a new directory named X inside the current directory.
mv A BMove a file from path A to path B. Also used for renaming files.
Moving between directories folder1 and folder2:
mv ./folder1/file.txt ./folder2
The file name will remain unchanged and its new path will be ./folder2/file.txt.
Renaming a file: mv new_doc.txt expenses.txt
The new file name is expenses.txt.
cp A BCopy a file from path A to path B. Usage similar to mv both in moving to a new directory and simultaneously renaming the file in its new location.
Example: cp ./f1/file.txt ./f2/expenses.txt simultaneously copies the file file.txt to the new location with a new name expenses.txt.
cp -r Y ZRecursively copy a directory Y and its contents to Z. If Z exists, copy source Y into it; otherwise, create Z and Y becomes its subdirectory with Y’s contents
rm XRemove (delete) X permanently.
rm -r YRecursively delete a directory Y and its contents
rm -f XForcibly remove file X without prompts or confirmation
rm -rf YForcibly remove directory Y and its contents recursively
rmdir YRemove a directory Y permanently, provided Y is empty.
duShow file/folder sizes on disk.
du -ahDisk usage in human readable format (KB, MB etc.)
du -shTotal disk usage of the current directory
dfDisplay free disk space.
du -hFree and used space on mounted filesystems
du -iFree and used inodes on mounted filesystems
open XOpen X in its default program.
open -e XOpens X in the default text editor (macOS: TextEdit)
touch XCreate an empty file X or update the access and modification times of X.
cat XView contents of X.
cat -b XAlso display line numbers as well.
wc XDisplay word count of X.
head XDisplay the first lines of X. If more than a single file is specified, each file is preceded by a header consisting of the string "==> X <=='' where "X'' is the name of the file.
head -n 4 XShow the first 4 lines of X.
ls *.c | head -n 5Display the first 5 items of a list of *.c files in the current directory.
tail XDisplay the last part of X. If more than a single file is specified, each file is preceded by a header consisting of the string "==> X <==" where "X" is the name of the file.
tail -n +1 XDisplay entire contents of the file(s) X specified, with header of respective file names
lessRead a file with forward and backward navigation. Often used with pipe e.g. cat file.txt | less
ln -s A SCreate symbolic link of path A to link name S.

Search and Filter

grep patt XSearch for a text pattern patt in X. Commonly used with pipe e.g. ps aux | grep python3 filters out the processes containing python3 from all running processes of all users.
grep -v patt XReturn lines not matching the specified patt.
grep -l patt XOnly the names of files containing patt are written to standard output.
grep -i patt XPerform case-insensitive matching. Ignore the case of patt.
findFind files.
find /path/to/src -name "*.sh"Find all files in /path/to/src matching the pattern "*.sh" in the file name.
find .. -size +2MFind all files in the parent directory larger than 2MB.
locate nameFind files and directories by name.
sort XArrange lines of text in X alphabetically or numerically.


tarManipulate archives with TAR extension.
tar -cf archive.tar YCreate a TAR archive named archive.tar containing Y.
tar -xf archive.tarExtract the TAR archive named archive.tar.
tar -tf archive.tarList contents of the TAR archive named archive.tar.
tar -czf archive.tar.gz YCreate a gzip-compressed TAR archive named archive.tar.gz containing Y.
tar -xzf archive.tar.gzExtract the gzip-compressed TAR archive named archive.tar.gz.
tar -cjf archive.tar.bz2 YCreate a bzip2-compressed TAR archive named archive.tar.bz2 containing Y.
tar -xjf archive.tar.bz2Extract the bzip2-compressed TAR archive named archive.tar.bz2.
zip -r Z.zip YZip Y to the ZIP archive Z.zip.
unzip Z.zipUnzip Z.zip to the current directory.

File Transfer

These are for uploading and downloading files.

ssh user@accessConnect to access as user.
ssh accessConnect to access as your local username.
ssh -p port user@accessConnect to access as user using port.
scp [user1@]host1:[path1] [user2@]host2:[path2]Login to hostN as userN via secure copy protocol for N=1,2. path1 and path2 may be local or remote. If user1 and user2 are not specified, your local username will be used.
scp -P port [user1@]host1:[path1] [user2@]host2:[path2] Connect to hostN as userN using port for N=1,2.
scp -r [user1@]host1:[path1] [user2@]host2:[path2]Recursively copy all files and directories from path1 to path2.
sftp [user@]accessLogin to access as user via secure file transfer protocol. If user is not specified, your local username will be used.
sftp accessConnect to access as your local username.
sftp -P port user@accessConnect to access as user using port.

File Permissions

Not all files are equally accessible. To prevent unwanted tampering, some files on your device may be read-only. For more information about file permissions on Unix, refer to our Linux File Permissions Cheat Sheet, as the same content applies to Unix.

Unix/Linux file permissions
File permissions on Unix
chmod permission fileChange permissions of a file or directory. Permissions may be of the form [u/g/o/a][+/-/=][r/w/x] (see examples below) or a three-digit octal number.
chown user2 fileChange the owner of a file to user2.
chgrp group2 fileChange the group of a file to group2.

Usage examples:

  • chmod +x testfile → allow all users to execute the file
  • chmod u-w testfile → forbid the current user from writing or changing the file
  • chmod u+wx,g-x,o=rx testfile → simultaneously add write & execute permissions to user, remove execute permission from group, and set the permissions of other users to only read and write.

Numeric Representation

OctalPermission(s)Equivalent to application of
0No permissions-rwx
1Execute permission only=x
2Write permission only=w
3Write and execute permissions only: 2 + 1 = 3=wx
4Read permission only=r
5Read and execute permissions only: 4 + 1 = 5=rx
6Read and write permissions only: 4 + 2 = 6=rw
7All permissions: 4 + 2 + 1 = 7=rwx


  • chmod 777 testfile → allow all users to execute the file
  • chmod 177 testfile → restrict current user (u) to execute-only, while the group (g) and other users (o) have read, write and execute permissions
  • chmod 365 testfile → user (u) gets to write and execute only; group (g), read and write only; others (o), read and execute only.

Process Management

The following is redolent of functions in Windows’ Task Manager, but on the command line.

&Add this character to the end of a command/process to run it in the background.
psShow process status. Often used with grep e.g. ps aux | grep python3 displays information on processes involving python3.

Meaning of aux:
a = show processes for all users
u = show user or owner column in output
x = show processes not attached to a terminal
ps -e
ps -A
Either of these two commands prints all running processes in the system.
ps -efPrint detailed overview.
ps -U root -u rootDisplay all processes running under the account root.
ps -eo pid,user,commandDisplay only the columns PID, USER and COMMAND in ps output.
topDisplay sorted information about processes.
kill PIDKill a process specified by its process ID PID, which you may obtain using the ps command.
lsofList all open files on the system. (This command helps you pinpoint what files and processes are preventing you from successfully ejecting an external drive.)


These commands regulate how your Unix machine communicates with other computers, such as the local area network (LAN) router or external websites.

ifconfigDisplay all network interfaces with IP addresses
netstatPrint open sockets of network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.

This command is often piped with the less command:
e.g. netstat -a | less
netstat -aShow both listening and non-listening sockets.
netstat -lShow only listening sockets, which are omitted by default.
ping hostSend ICMP echo request to host, which may be a symbolic name, domain name or IP address.
whois domainDisplay whois information for domain.
dig domainDisplay DNS information for domain.
host domainDisplay DNS IP address for domain.
wget LINKDownload from location LINK.
curl LINKDisplay the HTML source of LINK.

Vi Editor - Basic Commands

Built into Unix systems, vi (or vim) is a command-line visual editor. For simple text file manipulation, the following commands will suffice.

In the Unix terminal:

vi XCreate a new file X in the vi editor, or open X if X already exists.
vi -R X
view X
Open an existing file X in read-only mode.

While using vi editor (command mode):

:qQuit the vi editor.
:q!Quit the vi editor without saving changes.
:wSave changes.
:w filenameSave the file as filename.
:wqSave changes and quit vi editor.
iEnter insert mode and amend the opened file. To return to command mode and use the other commands in this table, press the ESC key.
oEnter insert mode and add a new line underneath the cursor.
xDelete the character under the cursor location.
ddDelete the line where the cursor is located.
rReplace the character under the cursor location with the key the user presses next.
yyCopy the current line.
pPaste the line that was copied beneath the cursor.
0Go to the beginning of the line.
$Go to the end of the line.
h,j,k,lMove the cursor left, down, up, right respectively.
GJump to the first character of the last line of the file.
ggJump to the first character of the first line of the file.
/fooSearch for instances of “foo” in the open file.
:%s/foo/barReplace every instance of “foo” with “bar” in the open file.

Shell Programming - Basic Commands

The file extension for shell scripts is .sh.

echo $VARDisplay the contents of a variable.
read VARGet standard input and save it to variable VAR.
#Designates all text after # on the same line to be comments (not executed).
#!/bin/shAlert the system that a shell script is being executed. Used as the first line of the shell script.


Valid Shell variable names contain alphanumeric [A-Z, a-z, 0-9] characters and/or underscore (_). The variable must begin an alphabetical character and is usually uppercase.

VAR_NAME=VALUEDefine a variable VAR_NAME and give it a VALUE. The value may be a number or string enclosed by double quotation marks ("). Examples:
PERSON="John Smith"
readonly VAR_NAMEMake the variable VAR_NAME read-only.
unset VAR_NAMEDelete the variable VAR_NAME.
$VAR1$VAR2Concatenate the values of the variables $VAR1 and $VAR2.

Reserved Variables

By using any of the following in your shell scripts, you call values from special variables in Unix.

$0File name of the current shell script.
$1, $2, $3, …, ${10}, ${11}, …References to the arguments supplied to the script: $1 is the first argument, $2 is the second argument, and so on.
$#The number of arguments supplied to a script.
$*Refer to arguments separated by spaces. Here, "a b c" d e are considered 5 separate arguments.
"$@"Refer to arguments grouped by the double quotes enclosing them. Here, "a b c" d e are considered 3 arguments.
$?The exit status of the last command executed: 0 for success and 1 or other numbers for various errors.
$$Process ID of the shell script.
$!Process number of the last background command.


In ksh shell: set -A ARRAY_NAME value1 value2 ... valueN

In bash shell: ARRAY_NAME=(value1 ... valueN)

Accessing array values (zero-indexed, i.e. first element is at [0] not [1]):

Array variableDescription
${ARRAY_NAME[index]}Display the value at [index] of ARRAY_NAME.
${ARRAY_NAME[*]}Display all values of the array ARRAY_NAME.
${ARRAY_NAME[@]}Same as ${ARRAY_NAME[*]}.

Basic Operators

These are used in the expressions in decision making and loop control.

For arithmetic and relational operators, the arguments are applied to both sides of each operator, separated by spaces, e.g. 2 + 2 (not 2+2).

Arithmetic operatorDescription
Relational operatorDescription
-eqEqual to
-neNot equal to
-gtGreater than
-ltLess than
-geGreater than or equal to
-leLess than or equal to
Boolean operatorDescription
!Logical negation / not: inverts true/false condition
-oLogical OR (inclusive): returns true if any one of the operands is true
-aLogical AND: returns true if all operands are true
String operatorDescription
=Returns true if the two operands on both sides of = are equal.
!=Returns true if the two operands on both sides of != are not equal.
-z $STRING_VARReturns true if $STRING_VAR is zero in length.
-n $STRING_VARReturns true if $STRING_VAR is not zero in length.
[ $STRING_VAR ]Returns true if $STRING_VAR is not the empty string.

In the following, FILE is a variable containing a string to a file/directory path.

File operatorDescription
-d $FILEReturns true if FILE is a directory.
-f $FILEReturns true if FILE is an ordinary file as opposed to a directory or special file.
-r $FILEReturns true if FILE is readable.
-w $FILEReturns true if FILE is writable.
-x $FILEReturns true if FILE is executable.
-e $FILEReturns true if FILE exists, even if FILE is a directory.
-s $FILEReturns true if FILE size is greater than zero.

Decision Making

if…fiif [ expression ]

   Statement(s) to be executed if expression is true
if…else…fiif [ expression ]

   Statement(s) to be executed if expression is true
   Statement(s) to be executed if expression is false
if…elif…else…fiif [ expression1 ]
Statement(s) to be executed if expression1 is true
elif [ expression2 ]
Statement(s) to be executed if expression2 is true
elif [ expression3 ]
Statement(s) to be executed if expression3 is true
Statement(s) to be executed if none of the given expressions is true
case…esaccase word in
Statement(s) to be executed if pattern1 matches word
Statement(s) to be executed if pattern2 matches word
Statement(s) to be executed if pattern3 matches word
Default condition to be executed

Loop Control

Loop typeSyntax
forfor VAR in word1 word2 … wordN
Statement(s) to be executed for every word

Note: word1 word2 … wordN may be a list of numbers (e.g. 1 2 3 4 5) or a set of paths (e.g. /home/folder*/app/).
whilewhile command
Statement(s) to be executed if command is true

Infinite loop: use : as the command, i.e. while :.
untiluntil command
Statement(s) to be executed until command is true
selectAvailable in ksh and bash but not sh. Behaves like a for-loop with the numbers replaced by the words.

select VAR in word1 word2 ... wordN
Statement(s) to be executed for every word
Flow controlSyntax
breakExit a loop.
continueExit the current iteration of the loop and proceed with the next iteration.
Ctrl+CKey combination to abort a running process
Ctrl+LKey combination to remove the previous command and its output (macOS: command+L)


This article covers all the basic commands you need to know when learning to operate Unix from the command line. We hope this Unix command cheat sheet is an excellent addition to your programming and cybersecurity toolkit. See Unix commands in action with our Complete Cyber Security Course available with a StationX Membership.

Frequently Asked Questions

Level Up in Cyber Security: Join Our Membership Today!

vip cta image
vip cta details
  • Cassandra Lee

    Cassandra is a writer, artist, musician, and technologist who makes connections across disciplines: cyber security, writing/journalism, art/design, music, mathematics, technology, education, psychology, and more. She's been a vocal advocate for girls and women in STEM since the 2010s, having written for Huffington Post, International Mathematical Olympiad 2016, and Ada Lovelace Day, and she's honored to join StationX. You can find Cassandra on LinkedIn and Linktree.

  • Anil says:

    This is such an awesome compilation, neatly organized. Thank you Miss C.

  • >