System Information
These provide information about your Unix machine.
Command Description
uname Show the Unix system information.
uname -a Detailed Unix system information
uname -r Kernel release information, such as kernel version
uptime Show how long the system is running and load information.
who Display who is logged in.
w Display what users are online and what they are doing.
users List current users.
whoami Display what user you are logged in as.
su Superuser; use this before a command that requires root access e.g. su shutdown
cal Show calendar where the current date is highlighted.
date Show the current date and time of the machine.
halt Stop the system immediately.
shutdown Shut down the system.
reboot Restart the system.
last reboot Show reboot history.
man COMMAND Shows 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.
Command Description
echo TEXT Display a line of TEXT or the contents of a variable.
echo -e TEXT Also interprets escape characters in TEXT, e.g. \n → new line, \b → backslash, \t → tab.
echo -n TEXT Omits trailing newline of TEXT.
| is the pipe character; feeds the output of the command cmd1 and sends it to the command cmd2, e
cmd1 | cmd2
grep python3.
cmd > file Output of cmd is redirected to file. Overwrites pre-existing content of file.
cmd >
Suppress the output of cmd.
/dev/null
cmd >> file Output of cmd is appended to file.
cmd < file Input of cmd is read from file.
Input of cmd is read from the standard input with the delimiter character delim to tell the system wh
terminate the input. Example for counting the number of lines of ad-hoc input:
wc -l << EOF
> I like
> apples
cmd << delim
> and
> oranges.
> EOF
4
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.
Command Description
* 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, et
List the names of files and subfolders in the current directory. Options include -l, -a, -t which may be
ls
e.g. -alt.
Also show details of each item displayed, such as user permissions and the time/date when the item
ls -l
modified.
ls -a Also display hidden files/folders. May be combined with ls -l to form ls -al.
ls -t Sort the files/folders according to the last modified time/date, starting with the most recently modifi
ls X List the files
Change directory to Y. Special instances of Y:
cd Y . — current directory
.. — parent directory
cd To the $HOME directory
cd .. Up one level to enclosing folder / parent directory
cd /etc To the /etc directory
Compare two files A and B for sameness. No output if A and B are identical, outputs character and lin
cmp A B
otherwise.
diff A B Compare two files A and B for differences. Outputs the difference.
pwd Display the path of the current working directory.
mkdir X Make a new directory named X inside the current directory.
Command Description
Move a file from path A to path B. Also used for renaming files.
Examples:
Moving between directories folder1 and folder2:
mv A B 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.
Copy a file from path A to path B. Usage similar to mv both in moving to a new directory and simulta
renaming the file in its new location.
cp A B
Example: cp ./f1/file.txt ./f2/expenses.txt simultaneously copies the file file.txt to the new location w
name expenses.txt.
Recursively copy a directory Y and its contents to Z. If Z exists, copy source Y into it; otherwise,
cp -r Y Z
create Z and Y becomes its subdirectory with Y’s contents
rm X Remove (delete) X permanently.
rm -r Y Recursively delete a directory Y and its contents
rm -f X Forcibly remove file X without prompts or confirmation
rm -rf Y Forcibly remove directory Y and its contents recursively
rmdir Y Remove a directory Y permanently, provided Y is empty.
du Show file/folder sizes on disk.
du -ah Disk usage in human readable format (KB, MB etc.)
du -sh Total disk usage of the current directory
df Display free disk space.
du -h Free and used space on mounted filesystems
Command Description
du -i Free and used inodes on mounted filesystems
open X Open X in its default program.
open -e X Opens X in the default text editor (macOS: TextEdit)
touch X Create an empty file X or update the access and modification times of X.
cat X View contents of X.
cat -b X Also display line numbers as well.
wc X Display word count of X.
Display the first lines of X. If more than a single file is specified, each file is preceded by a header con
head X
the string "==> X <=='' where "X'' is the name of the file.
head -n 4 X Show the first 4 lines of X.
ls *.c | head -
Display the first 5 items of a list of *.c files in the current directory.
n5
Display the last part of X. If more than a single file is specified, each file is preceded by a header cons
tail X
the string "==> X <==" where "X" is the name of the file.
tail -n +1 X Display entire contents of the file(s) X specified, with header of respective file names
less Read a file with forward and backward navigation. Often used with pipe e.g. cat file.txt | less
ln -s A S Create symbolic link of path A to link name S.
Start Your Cyber Security Career with StationX
• 1000+ Classes & Virtual Labs
• Top Certification Prep
• Mentorship & Career Support
• Community Access
• Advanced Training & Networking
MEMBERSHIP →
00
days
03
hrs
13
mins
49
secs
Search and Filter
Command Description
Search for a text pattern patt in X. Commonly used with pipe e.g. ps aux | grep python3 filter
grep patt X
processes containing python3 from all running processes of all users.
grep -v patt X Return lines not matching the specified patt.
grep -l patt X Only the names of files containing patt are written to standard output.
grep -i patt X Perform case-insensitive matching. Ignore the case of patt.
find Find files.
find /path/to/src -
Find all files in /path/to/src matching the pattern "*.sh" in the file name.
name "*.sh"
find .. -size +2M Find all files in the parent directory larger than 2MB.
locate name Find files and directories by name.
Command Description
sort X Arrange lines of text in X alphabetically or numerically.
Archives
Command Description
tar Manipulate archives with TAR extension.
tar -cf archive.tar Y Create a TAR archive named archive.tar containing Y.
tar -xf archive.tar Extract the TAR archive named archive.tar.
tar -tf archive.tar List contents of the TAR archive named archive.tar.
tar -czf archive.tar.gz Y Create a gzip-compressed TAR archive named archive.tar.gz containing Y.
tar -xzf archive.tar.gz Extract the gzip-compressed TAR archive named archive.tar.gz.
tar -cjf archive.tar.bz2 Y Create a bzip2-compressed TAR archive named archive.tar.bz2 containing Y.
tar -xjf archive.tar.bz2 Extract the bzip2-compressed TAR archive named archive.tar.bz2.
zip -r Z.zip Y Zip Y to the ZIP archive Z.zip.
unzip Z.zip Unzip Z.zip to the current directory.
File Transfer
These are for uploading and downloading files.
Command Description
ssh user@access Connect to access as user.
ssh access Connect to access as your local username.
ssh -p port user@access Connect to access as user using port.
Command Description
scp [user1@]host1:[path1] Login to hostN as userN via secure copy protocol for N=1,2. path1 and path2
[user2@]host2:[path2] local or remote. If user1 and user2 are not specified, your local username wil
scp -P port [user1@]host1:[path1]
Connect to hostN as userN using port for N=1,2.
[user2@]host2:[path2]
scp -r [user1@]host1:[path1]
Recursively copy all files and directories from path1 to path2.
[user2@]host2:[path2]
Login to access as user via secure file transfer protocol. If user is not specified
sftp [user@]access
username will be used.
sftp access Connect to access as your local username.
sftp -P port user@access Connect 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.
File permissions on Unix
Command Description
chmod permission Change permissions of a file or directory. Permissions may be of the form [u/g/o/a][+/-/=][r/w/x
file examples below) or a three-digit octal number.
Command Description
chown user2 file Change the owner of a file to user2.
chgrp group2 file Change 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
Octal Permission(s) Equivalent to application of
0 No permissions -rwx
1 Execute permission only =x
2 Write permission only =w
3 Write and execute permissions only: 2 + 1 = 3 =wx
4 Read permission only =r
5 Read and execute permissions only: 4 + 1 = 5 =rx
6 Read and write permissions only: 4 + 2 = 6 =rw
7 All permissions: 4 + 2 + 1 = 7 =rwx
Examples
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.
Command Description
& Add this character to the end of a command/process to run it in the background.
Show process status. Often used with grep e.g. ps aux | grep python3 displays information o
processes involving python3.
ps 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
Either of these two commands prints all running processes in the system.
ps -A
ps -ef Print detailed overview.
ps -U root -u root Display all processes running under the account root.
ps -eo
Display only the columns PID, USER and COMMAND in ps output.
pid,user,command
top Display sorted information about processes.
kill PID Kill a process specified by its process ID PID, which you may obtain using the ps command.
List all open files on the system. (This command helps you pinpoint what files and processes
lsof
preventing you from successfully ejecting an external drive.)
Networking
These commands regulate how your Unix machine communicates with other computers, such as the
local area network (LAN) router or external websites.
Command Description
ifconfig Display all network interfaces with IP addresses
Print open sockets of network connections, routing tables, interface statistics, masquerade connectio
multicast memberships.
netstat
This command is often piped with the less command:
e.g. netstat -a | less
netstat -a Show both listening and non-listening sockets.
netstat -l Show only listening sockets, which are omitted by default.
ping host Send ICMP echo request to host, which may be a symbolic name, domain name or IP address.
whois
Display whois information for domain.
domain
dig domain Display DNS information for domain.
host domain Display DNS IP address for domain.
wget LINK Download from location LINK.
curl LINK Display 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:
Command Description
vi X Create a new file X in the vi editor, or open X if X already exists.
Command Description
vi -R X
Open an existing file X in read-only mode.
view X
While using vi editor (command mode):
Command Description
:q Quit the vi editor.
:q! Quit the vi editor without saving changes.
:w Save changes.
:w filename Save the file as filename.
:wq Save changes and quit vi editor.
Enter insert mode and amend the opened file. To return to command mode and use the other comman
i
table, press the ESC key.
o Enter insert mode and add a new line underneath the cursor.
x Delete the character under the cursor location.
dd Delete the line where the cursor is located.
r Replace the character under the cursor location with the key the user presses next.
yy Copy the current line.
p Paste the line that was copied beneath the cursor.
0 Go to the beginning of the line.
$ Go to the end of the line.
Command Description
h,j,k,l Move the cursor left, down, up, right respectively.
G Jump to the first character of the last line of the file.
gg Jump to the first character of the first line of the file.
/foo Search for instances of “foo” in the open file.
:%s/foo/bar Replace every instance of “foo” with “bar” in the open file.
Shell Programming - Basic Commands
The file extension for shell scripts is .sh.
Command Description
echo $VAR Display the contents of a variable.
read VAR Get standard input and save it to variable VAR.
# Designates all text after # on the same line to be comments (not executed).
#!/bin/sh Alert the system that a shell script is being executed. Used as the first line of the shell script.
Other Links You Might Like:
Linux File Permissions Cheat Sheet
Linux Command Line Cheat Sheet
Bash Cheat Sheet
Tmux Cheat Sheet
Tcpdump Cheat Sheet
Vi Cheat Sheet
Our Linux Courses Collection
Variables
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.
Command Description
Define a variable VAR_NAME and give it a VALUE. The value may be a number or string enclos
double quotation marks ("). Examples:
VAR_NAME=VALUE
PRICE=100
PERSON="John Smith"
readonly VAR_NAME Make the variable VAR_NAME read-only.
unset VAR_NAME Delete the variable VAR_NAME.
$VAR1$VAR2 Concatenate 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.
Variable Description
$0 File name of the current shell script.
$1, $2, $3, …, ${10}, References to the arguments supplied to the script: $1 is the first argument, $2 is the sec
${11}, … 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 argu
Refer to arguments grouped by the double quotes enclosing them. Here, "a b c" d e are c
"$@"
3 arguments.
The exit status of the last command executed: 0 for success and 1 or other numbers for v
$?
errors.
$$ Process ID of the shell script.
$! Process number of the last background command.
Variable Description
Arrays
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 variable Description
${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[*]}.
Start Your Cyber Security Career with StationX
• 1000+ Classes & Virtual Labs
• Top Certification Prep
• Mentorship & Career Support
• Community Access
• Advanced Training & Networking
MEMBERSHIP →
00
days
03
hrs
13
mins
49
secs
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 operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
= Assignment
== Equality
!= Inequality
Relational operator Description
-eq Equal to
-ne Not equal to
-gt Greater than
-lt Less than
-ge Greater than or equal to
-le Less than or equal to
Boolean operator Description
! Logical negation / not: inverts true/false condition
-o Logical OR (inclusive): returns true if any one of the operands is true
-a Logical AND: returns true if all operands are true
String operator Description
= 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_VAR Returns true if $STRING_VAR is zero in length.
-n $STRING_VAR Returns 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 operator Description
-d $FILE Returns true if FILE is a directory.
-f $FILE Returns true if FILE is an ordinary file as opposed to a directory or special file.
-r $FILE Returns true if FILE is readable.
-w $FILE Returns true if FILE is writable.
-x $FILE Returns true if FILE is executable.
-e $FILE Returns true if FILE exists, even if FILE is a directory.
-s $FILE Returns true if FILE size is greater than zero.
Decision Making
Types Syntax
if [ expression ]
then
if…fi
Statement(s) to be executed if expression is true
fi
if [ expression ]
then
Statement(s) to be executed if expression is true
if…else…fi
else
Statement(s) to be executed if expression is false
fi
if [ expression1 ]
then
Statement(s) to be executed if expression1 is true
elif [ expression2 ]
then
Statement(s) to be executed if expression2 is true
if…elif…else…fi
elif [ expression3 ]
then
Statement(s) to be executed if expression3 is true
else
Statement(s) to be executed if none of the given expressions is true
fi
case…esac case word in
pattern1)
Statement(s) to be executed if pattern1 matches word
;;
pattern2)
Statement(s) to be executed if pattern2 matches word
;;
pattern3)
Statement(s) to be executed if pattern3 matches word
;;
*)
Default condition to be executed
;;
Types Syntax
esac
Loop Control
Loop type Syntax
for VAR in word1 word2 … wordN
do
Statement(s) to be executed for every word
for
done
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
while command
do
Statement(s) to be executed if command is true
while
done
Infinite loop: use : as the command, i.e. while :.
until command
do
until
Statement(s) to be executed until command is true
done
Available 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
select
do
Statement(s) to be executed for every word
done
Flow control Syntax
break Exit a loop.
continue Exit the current iteration of the loop and proceed with the next iteration.
Flow control Syntax
Ctrl+C Key combination to abort a running process
Ctrl+L Key combination to remove the previous command and its output (macOS: command+L)