Unix Commands Cheat Sheet
Unix Commands Cheat Sheet
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.
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.
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.
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 > 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.
cmd << delim Input 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.
> 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.
* 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.
ls List the names of files and subfolders in the current directory.
Options include -l, -a, -t which may be combined e.g. -alt.
ls -l Also show details of each item displayed, such as user permissions
and the time/date when the item was last 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 modified item.
ls X List the files
cd Y Change directory to Y. Special instances of 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
cmp A B Compare two files A and B for sameness. No output if A and B are
identical, outputs character and line number 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.
mv A B Move a file from path A to path B. Also used for renaming files.
Examples:
- 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 B Copy 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.
grep patt X Search 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 Return lines not matching the specified patt.
X
grep -l patt Only the names of files containing patt are written to standard
X output.
grep -i patt Perform case-insensitive matching. Ignore the case of patt.
X
find Find files.
find Find all files in /path/to/src matching the pattern "*.sh" in the
/path/to/src file name.
-name "*.sh"
find .. -size Find all files in the parent directory larger than 2MB.
+2M
locate name Find files and directories by name.
Archives
File Transfer
These are for uploading and downloading files.
ssh Connect to access as user.
user@access
ssh access Connect to access as your local username.
ssh -p port Connect to access as user using port.
user@access
scp Login to hostN as userN via secure copy protocol for N=1,2.
[user1@]host1 path1 and path2 may be local or remote. If user1 and user2 are
:[path1] not specified, your local username will be used.
[user2@]host2
:[path2]
scp -P port Connect to hostN as userN using port for N=1,2.
[user1@]host1
:[path1]
[user2@]host2
:[path2]
scp -r Recursively copy all files and directories from path1 to path2.
[user1@]host1
:[path1]
[user2@]host2
:[path2]
sftp Login to access as user via secure file transfer protocol. If user is
\ [user@]access not specified, your local username will be used.
sftp access Connect to access as your local username.
sftp -P port Connect to access as user using port.
user@access
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.
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
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.
& Add this character to the end of a command/process to run it in the
background.
ps Show 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 Either of these two commands prints all running processes in the
ps -A system.
ps -ef Print detailed overview.
ps -U root -u Display all processes running under the account root.
root
ps -eo Display only the columns PID, USER and COMMAND in ps output.
pid,user,comm
and
top Display sorted information about processes.
kill PID Kill a process specified by its process ID PID, which may be obtained
using the ps command.
lsof List all open files on the system. (This command helps you pinpoint
what files and processes are 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.
ifconfig Display all network interfaces with IP addresses
netstat Print open sockets of network connections, routing tables, interface
statistics, masquerade connections, and multicast memberships
:w Save changes.
:w filename Save the file as filename.
i Enter insert mode and amend the opened file. To return to command
mode and use the other commands in this table, press the ESC key.
o Enter insert mode and add a new line underneath the cursor.
r Replace the character under the cursor location with the key the user
presses next.
:%s/foo/bar Replace every instance of “foo” with “bar” in the open file.
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.
Reserved Variables
By using any of the following in your shell scripts, you call values from special variables in
Unix.
$0 File name of the current shell script.
$1, $2, $3, …, References to the arguments supplied to the script: $1 is
${10}, ${11}, … 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.
Arrays
ksh: set -A ARRAY_NAME value1 value2 ... valueN
bash: ARRAY_NAME=(value1 ... valueN)
\
Accessing array values (zero-indexed, i.e. first element is at [0] not [1]):
${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).
Decision Making
Types Syntax
if…fi if [ expression ]
then
Statement(s) to be executed if expression is true
fi
if…else… if [ expression ]
fi then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is false
fi
if…elif… if [ expression1 ]
else…fi then
Statement(s) to be executed if expression1 is true
elif [ expression2 ]
then
Statement(s) to be executed if expression2 is true
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…esa case word in
c 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
;;
esac
Loop Control
Conclusion
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 VIP membership.