Linux Commands Cheat Sheet (For CompTIA Linux+ and LPIC-1)

Linux Cheat Sheet

Lost the TAR flags again? Or maybe you’re new to Linux and need the top terminal commands for files, folders, networking, and security. With so many utilities, it’s easy to feel overwhelmed.

This Linux Commands Cheat Sheet article serves both as a complete Linux cheat sheet and a practical study guide for CompTIA Linux+ and LPIC-1. We’ve organized the essentials by task - file and archive management (yes, all the TAR basics), permissions & ownership, processes & services, networking & troubleshooting, package management, and common security commands, so you can find what you need fast and build real command-line confidence. Download the cheat sheet here, keep it by your terminal, and scroll below to jump straight to the commands you need today.

Linux Command Line Cheat Sheet Search

Search our Linux Command Line 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

We recommend that you memorize these commands. You’ll need them the most when operating Linux.

Shells and Environment

The shell controls how users interact with Linux. These commands manage environment variables, aliases, and the way the system interprets commands.

CommandDescription
echo $SHELLDisplay the current user’s shell.
envShow current environment variables.
setDisplay all shell variables and functions.
export VAR=valueSet an environment variable for child processes.
alias ll='ls -la'Create an alias (example: ll for ls -la).
unalias llRemove an alias.
which commandShow the path to an executable.
type commandDisplay how the shell interprets a command (alias, function, builtin, or file).
Shells and Environment

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.

CommandDescription
*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 you may combine, 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 
stat fileDisplay detailed file metadata (permissions, timestamps, inode, size).
file nameShow the file type (binary, text, symlink, directory).
pwdDisplay the path of the current working directory.
realpath filePrint the absolute path of a file.
basename pathStrip directory info, leaving only the filename.
dirname pathStrip filename, leaving only the directory path.
readlink -f fileShow the actual target of a symbolic link.
cd YChange directory to Y.

Special instances of Y:
.  â€” current directory
.. — parent directory
cdTo the $HOME directory
cd ..Up one level to enclosing folder or 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.
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.
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 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.
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 10 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 (10, by default) 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.
tail -n +1 XDisplay entire contents of the file(s) X specified, with header of respective file names
tail -f XDisplay the last 10 lines of the file(s) X specified, and track changes appended to them at the end. Overwriting X or modifying X with a text editor such as vim would mess up this command’s output.
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.
/boot, /proc, /sys, /var, /usr, /home, /opt, /tmpImportant FHS directories.
File Management
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image
Slider Image

Printing

Linux supports printing through various commands to send files to printers, check queues, and manage print jobs.

CommandDescription
lp filePrint a file using the default printer.
lpr filePrint a file (alternative command).
lpqShow print queue status.
lprm job-idRemove a job from the print queue.

Input/Output Redirection

These are helpful for logging program output and error messages, and are essential topics in CompTIA Linux+ and LPIC-1.

CommandDescription
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.
tee fileWrite output to both standard output and a file simultaneously.
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 > fileRedirect output of a command cmd to a file file. Overwrites pre-existing content of file.
2>&1Redirect standard error to standard output.
cmd >& fileRedirect output of cmd to file. Overwrites pre-existing content of file. Suppresses the output of cmd.
cmd > /dev/nullSuppress the output of cmd.
cmd >> fileAppend output of cmd to file.
cmd < fileRead input of cmd from file.
cmd << delimRead input of cmd 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.
cmd <<< stringInput a text string to cmd.
cmd 2> fooRedirect error messages of cmd to foo.
cmd 2>> fooAppend error messages of cmd to foo.
cmd &> fileRedirect output and error messages of cmd to file.
&Run a command in the background.
InputOutput Redirection

Search and Filter

These commands help you find the files you want.

CommandDescription
grep patt /path/to/srcSearch 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 -r patt /path/to/srcSearch recursively (the target directory /path/to/src and its subdirectories) for a text pattern patt.
grep -v patt XReturn lines in X not matching the specified patt.
grep -l patt XWrite to standard output the names of files containing patt.
grep -i patt XPerform case-insensitive matching on X. Ignore the case of patt.
grep -A n / grep -B n / grep -C nShow lines After, Before, or Context around a match.
grep -EUse extended regular expressions for more complex searches.
findFind files.
find /path/to/src -name "*.sh"Find all files in /path/to/src matching the pattern "*.sh" in the file name.
find /home -size +100MFind all files in the /home directory larger than 100MB.
locate nameFind files and directories by name.
sort XArrange lines of text in X alphabetically or numerically.
awk '{print $1, $2}' fileExtract and process fields from structured text.
cut -d: -f1 /etc/passwdExtract fields by delimiter.
tr 'a-z' 'A-Z'Translate characters (e.g., lowercase to uppercase).
uniq fileFilter out duplicate lines from sorted output.
Search and Filter

Text Processing

Working with text files is a core part of Linux administration. These commands let you view, edit, sort, search, and transform text efficiently.

CommandDescription
head -n 10 fileDisplay the first 10 lines of a file.
tail -n 10 fileDisplay the last 10 lines of a file.
wc -l fileCount lines in a file.
cut -d: -f1 /etc/passwdExtract fields from text (example: usernames from /etc/passwd).
sort fileSort lines in a file alphabetically or numerically.
uniq fileRemove duplicate lines (often used with sort).
tr a-z A-ZTranslate or replace characters (example: convert lowercase to uppercase).
grep pattern fileSearch for a pattern in a file.
egrep pattern fileUse extended regex patterns.
fgrep string fileSearch for fixed strings (faster than regex).
sed 's/foo/bar/g' fileStream editor: replace "foo" with "bar".
awk '{print $1}' filePrint the first column of each line.
Text Processing

Archives

These commands are for unpacking compressed files (.zip, .gz, .bz2, .tar, etc.) with large or complex contents, such as programs. TAR commands, in particular, can be tricky to remember.

CommandDescription
tarManipulate archives with .tar extension.
tar -vGet verbose output while manipulating TAR archives. May combine this option with others, e.g., tar -tvf.
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 archiave.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.
tar -cJf archive.tar.xz dirCreate an XZ-compressed tar archive.
tar -xJf archive.tar.xzExtract an XZ-compressed tar archive.
tar --zstd -cf archive.tar.zst dirCreate a Zstandard-compressed tar archive
tar --zstd -xf archive.tar.zstExtract a Zstandard-compressed tar archive.
tar --exclude=patternExclude files from an archive.
gzipManipulate archives with .gz extension.
gzip YCreate a gzip archive named Y.gz containing Y.
gzip -l Y.gzList contents of gzip archive Y.gz.
gzip -d Y.gz
gunzip Y.gz
Extract Y.gz and recover the original file Y.
gzip fileCompress a file using gzip.
gunzip file.gzDecompress a gzip file.
bzip2Manipulate archives with .bz2 extension.
bzip2 YCreate a bzip2 archive named Y.bz2 containing Y.
bzip2 -d Y.gz
bunzip2 Y.gz
Extract Y.bz2 and recover the original file Y.
bzip2 fileCompress a file using bzip2.
bunzip2 file.bz2Decompress a bzip2 file.
xz fileCompress a file using XZ.
unxz file.xzDecompress an XZ file.
zstd fileCompress a file using Zstandard.
unzstd file.zstExtract a Zstandard archive.
zip -r Z.zip YZip Y to the ZIP archive Z.zip.
unzip Z.zipUnzip Z.zip to the current directory.
unzip Z.zipList contents of Z.zip.
zip archive.zip filesCreate a zip archive.
7z file.7zCreate or extract a 7zip archive (if installed).
Archives

File Transfer

These commands are for logging in to local and remote hosts, and for uploading and downloading files, transferring them between devices. Remember to omit the square brackets "[" and "]" when you input the optional parameters they enclose.

CommandDescription
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.
ssh-copy-id user@hostCopy public key to a server for passwordless SSH login.
ssh -L local:remote:port user@hostCreate a local port forwarding tunnel over SSH.
ssh -D port user@hostCreate a dynamic SOCKS proxy over SSH.
scp [user1@]host1:[path1] [user2@]host2:[path2]Login to hostN as userN via secure copy protocol for N=1,2.

Example usage:
scp alice@pi:/home/source bob@arduino:/destination

path1 and path2 may be local or remote, but ensure they’re absolute rather than relative paths, e.g., /var/www/*.html, /usr/bin.

If user1 and user2 are not specified, scp will use your local username.
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.
scp -C file user@host:/pathCopy files over SSH with compression.
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.
rsync -a [path1] [path2]Synchronize [path1] to [path2], preserving symbolic links, attributes, permissions, ownerships, and other settings.
rsync -avz host1:[path1] [path2]Synchronize [path1] on the remote host host1 to the local path [path2], preserving symbolic links, attributes, permissions, ownerships, and other settings. It also compresses the data involved during the transfer.
rsync --delete src dstRemove extraneous files in the destination to mirror source.
rsync --progress src dstShow transfer progress during sync.
wget urlDownload a file from the web.
curl ‑O urlDownload a file keeping original filename.
curl ‑L urlFollow redirects when downloading.

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 Linux, refer to our Linux File Permissions Cheat Sheet.

Basic File Permissions

Linux file type - regular file, d directory, l symbolic link; scope u user, g group, o other, a all; permissions r read, w write, x execute
CommandDescription
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.
chmod u+x fileAdd execute permission for the owner.
chmod g-w fileRemove write permission from group.
chmod o=r fileSet others to read-only.
umask 022Show or set default permissions for new files.
getfacl fileView Access Control Lists on a file.
setfacl -m u:user:rw fileAdd ACL entry giving a user read/write access.
lsattr fileShow extended file attributes.
chattr +i fileMake a file immutable until attribute removed.

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 and execute permissions to user, remove execute permission from group, and set the permissions of other users to only read and write.
Usage examples

Numeric Representation

The table below compares Linux file permissions in octal form and in the format [u/g/o/a][+/-/=][r/w/x].

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
644rw-r--r--Typical default for files.
755rwxr-xr-xTypical default for directories and executables.
umask 022-Default new files get 644.
umask 027-Default new files get 640.

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.

Special Permission Bits

SUID (Set User ID): When set on an executable file, the program runs with the permissions of the file’s owner instead of the user running it. Example: /usr/bin/passwd.

  • Appears on the user/owner execute bit.
  • s = SUID + execute
  • S = SUID without execute
  • Example: -rwsr-xr-x → SUID set, owner can execute.

Example: -rwSr-xr-x → SUID set, owner cannot execute.

SGID (Set Group ID): On executables, runs with the group’s permissions. On directories, new files inherit the group of the directory instead of the creating user’s group.

  • Appears on the group execute bit.
  • s = SGID + execute
  • S = SGID without execute
  • Example: -rwxr-sr-x → SGID set, group can execute.
  • Example: -rwxr-Sr-x → SGID set, group cannot execute.

Sticky Bit: On directories (like /tmp), users can only delete or rename their own files, even if others have write access to the directory.

  • Appears on the others execute bit.
  • t = sticky + execute
  • T = sticky without execute
  • Example: drwxrwxrwt → world-writable directory with sticky bit (like /tmp).
  • Example: drwxrwxrwT → sticky set, others cannot execute.

Octal permissions are 4 digits:

[special][user][group][others]

Special digit (first one):

  • 4 = SUID
  • 2 = SGID
  • 1 = Sticky
  • Add them together if you want more than one (e.g., 6 = SUID + SGID, 7 = SUID + SGID + Sticky)
OctalSpecial BitPlacementWith ExecuteWithout Execute
4xxxSUIDUser Executerwsr-xr-x-rwSr-xr-x
2xxxSGIDGroup Executerwxr-sr-xrwxr-Sr-x
1xxxStickyOthers ExecutedrwxrwxrwtdrwxrwxrwT

xxx = regular owner/group/others permission digits (e.g., 755, 644).

System Information

These commands come in handy when you’re developing new applications for Linux or troubleshooting your Linux machine.

General

These provide information about your Linux machine and perform administrative tasks.

CommandDescription
unameShow the Linux system information.
uname -aDetailed Linux system information
uname -rKernel release information, such as kernel version
uptimeShow how long the system is running and load information.
su
sudo
Superuser; 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”.
hostnameShow system host name
hostname -IDisplay IP address of host
cat /etc/*-releaseShow the version of the Linux distribution installed. For example, if you’re using Red Hat Linux, you may replace * with redhat.
hostnamectlShow or set the system hostname.
timedatectlShow or set system date, time, and NTP.
localectlShow or set locale and keyboard layout.
whoShow who is logged in.
journalctl -bDisplay logs since last boot.
uptime -pShow uptime in human-readable form.
General System Information

Hardware

These commands provide details about the hardware supporting your Linux machine.

CommandDescription
dmesgDisplay messages in kernel ring buffer (data structure that records messages related to the operation of the program running the operating system)
cat /proc/cpuinfo Display information about the central processing unit (CPU)
cat /proc/meminfoDisplay memory information
lspci -tvDisplays information about each Peripheral Component Interconnect (PCI) device on your system.
The option -t outputs the information as a tree diagram, and -v is for verbose output.
lsusb -tvDisplay information about Universal Serial Bus (USB) devices and the devices connected to them.
The option -t outputs the information as a tree diagram, and -v is for verbose output.
dmidecodeDisplay system hardware components, serial numbers, and BIOS version
hdparm -i /dev/sdaDisplay information about the disk sda
hdparm -tT /dev/sdaPerform a read speed test on the disk sda 
badblocks -s /dev/sdaTest for unreadable blocks on the disk sda
lsblkList block devices and mount points.
blkidShow UUIDs and filesystem types.
lsscsiDisplay SCSI/SATA/NVMe devices.
lsmodList loaded kernel modules.
modinfo moduleShow details about a kernel module.
modprobe moduleLoad a kernel module.
rmmod moduleRemove a kernel module.
sensorsShow temperature/voltage/fan readings.
ls /devList device files.
ls -l /dev/null /dev/zeroDisplay details of special device files.
mount device dirMount a device (example: mount /dev/sda1 /mnt).
umount dirUnmount a device.
cat /etc/fstabShow static filesystem mount configuration

Disk Usage

These commands provide storage details regarding your Linux machine.

CommandDescription
dfDisplay free disk space.
df -TShow filesystem type along with disk usage.
duShow file/folder sizes on disk.
du -ahDisk usage in human readable format (KB, MB etc.)
du -shTotal disk usage of the current directory
du -hFree and used space on mounted filesystems
du -iFree and used inodes on mounted filesystems
du --max-depth=1 -hShow disk usage per directory.
du --max-depth=1 -hShow disk usage per directory.
fdisk -lList disk partitions, sizes, and types
parted -lList partitions and details (alternative to fdisk).
tune2fs -l /dev/sdXShow ext filesystem parameters.
e2fsck /dev/sdXCheck and repair ext filesystems.
xfs_info /mountpointDisplay XFS filesystem information.
mount /dev/sdX /mntMount a filesystem.
umount /mntUnmount a filesystem.
free -hDisplay free and used memory in human readable units.
free -mDisplay free and used memory in MB.
free -gDisplay free and used memory in GB.
swapoff / swaponDisable or enable swap.

Process Management and Performance Monitoring

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

CommandDescription
&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
htopDisplay sorted information about processes with visual highlights. It allows you to scroll vertically and horizontally, so you can see every process running on your system and entire commands.
atopDisplay detailed information about processes and hardware
kill PIDKill a process specified by its process ID PID, which you obtain using the ps command
killall proc1Kill all processes containing proc1 in their names
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.)
lsof -u rootList all files on the system opened by the root user. As the output can be long, you may use lsof -u root | less to keep this list from taking up space in the terminal output.
mpstat 1Display processor-related statistics, updated every second (hence the 1, whereas mpstat 2 refreshes the output every 2 seconds)
vmstat 1Display virtual memory statistics (information about memory, system processes, paging, interrupts, block I/O, disk, and CPU scheduling), updated every (1) second
iostat 1Display system input/output statistics for devices and partitions. virtual memory statistics, updated every (1) second
tail -n 100 /var/log/messagesDisplay the last 100 lines in the system logs.
Replace /var/log/messages with /var/log/syslog for Debian-based systems.
tcpdump -i eth0Capture and display all packets on interface eth0
tcpdump -i eth0 port 80Monitor all traffic on interface eth0 port 80 (HTTP)
watch df -hExecute df -h and show periodic updates.
To exit, press Ctrl+C.
jobsList jobs running in the background.
fg %1Bring job 1 to foreground.
bg %1Resume job 1 in background.
systemctl status serviceShow service status.
systemctl start/stop/enable/disable serviceStart, stop, enable, or disable a service.
systemctl list-units --type=serviceList active services.
journalctl -xeView recent logs with errors.
journalctl -u serviceView logs for a specific service.
nice -n 10 cmdRun a command with adjusted scheduling priority.
renice -n -5 -p PIDChange priority of a running process.
sar -u 1Display CPU usage statistics (if installed).

Job Control

These commands help you manage background and foreground processes, suspend jobs, and switch between them.

CommandDescription
jobsList background and suspended jobs.
bg %1Resume job 1 in the background.
fg %1Bring job 1 to the foreground.
Ctrl+ZSuspend the current foreground process.

User Management

These commands give information on the system’s users and allows superuser administrators to change user settings.

CommandDescription
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
idDisplay the user ID and group IDs of your current user
lastDisplay the last users who have logged onto the system
groupadd gp1Create a group named gp1
useradd -c "Alice Bob" -m ab1Create an account named ab1, with a comment of "Alice Bob" and create the new user’s home directory
userdel ab1Delete the account named ab1
usermod -aG gp1 ab1Add the account ab1 to the group gp1
passwd userSet or change a user’s password.
passwd -l userLock a user account.
passwd -u userUnlock a user account.
chage -l userDisplay account password expiry info.
chage -M 90 userSet password to expire every 90 days.
/etc/login.defsFile that sets user defaults (e.g., password aging).
/etc/skel/Default files copied to new user’s home.
/etc/passwdStores user account details.
/etc/shadowStores password hashes and aging info.
/etc/groupStores group definitions.
su - userSwitch to another user with their environment.
sudo -iStart a root login shell.
groups userShow groups the user belongs to.

Networking

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

CommandDescription
ifconfigDisplay all network interfaces with IP addresses
ifconfig -aDisplay all network interfaces, even if any of them is down, with IP addresses
ifconfig eth0Display IP addresses and details of the eth0 interface
ip aAnother way to display all network interfaces with IP addresses
ethtool eth0Query or control network driver and hardware settings of the interface eth0
netstatPrint open sockets of network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.
Pipe with the less command: e.g., netstat -a | less
netstat -aShow both listening and non-listening sockets
netstat -lShow only listening sockets
netstat -nutlpShow listening TCP and UDP ports and corresponding programs
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
dig -x addrDo a reverse lookup on an IPv4 or IPv6 address addr
host domainDisplay DNS IP address for domain
wget LINKDownload from location LINK
curl LINKDisplay the HTML source of LINK. Check out our curl Cheat Sheet for details.
ip link showShow network interfaces (modern replacement for ifconfig).
ss -tulwnShow listening TCP/UDP ports (modern replacement for netstat).
nmcliManage network connections via NetworkManager.
ip routeShow routing table.
traceroute hostTrace route packets take to a host.
mtr hostContinuous traceroute + ping statistics.
nslookup hostQuery DNS (legacy tool, still tested).
/etc/resolv.confFile containing DNS server config.
nmap -sT hostScan open TCP ports (basic knowledge expected).
firewall-cmd --list-allShow firewalld configuration.
ufw statusShow uncomplicated firewall status.

Installing New Programs

A package file is an archive containing compiled software and other resources it uses. The package file extension and the package installer (a utility for installing new programs) depend on the Linux distribution.

Know your system’s Linux distribution to understand the correct installation commands tailored to it. If the package comes with a README component, it should contain application-specific installation instructions such as extracting TAR files, ./setup.sh, and make install.

Package Management Overview

The following table is on package management in popular Linux distributions.

Linux DistributionPackage File ExtensionPackage Installer(s)Extra Information
Debian/Ubuntu.debapt, dpkgRepo configs: /etc/apt/sources.list, /etc/apt/sources.list.d/
Rocky / Fedora / Red Hat Enterprise Linux.rpmyum, dnfRepo configs: /etc/yum.repos.d/
Arch Linux / Manjaro / Garuda / Chakra.pkg, .pacman, .pkg.tar(.xz/.zst/.gz)pacmanPackage databases are in /var/lib/pacman/
Universal.snap, .flatpak, .AppImagesnap, flatpak, (run directly for AppImage)Snap (snap), Flatpak (flatpak), AppImage (run directly).

Package Management Commands

Here are the commands for package management in popular Linux distributions.

Linux distributionDebian / UbuntuRocky / Fedora / Red Hat Enterprise LinuxArch Linux / Manjaro / Garuda / Chakra
Update list of packages available from remote repositoriessudo apt updatednf check-updateThe command pacman -Syy achieves this purpose but may damage your system.
Use pacman -Syu instead.
Upgrade installed packagessudo apt upgradesudo dnf upgradepacman -Syu
Find a package with keyword in the nameapt search keyworddnf search keywordpacman -Ss keyword
View description and summary information about a packageapt show packagednf info packagepacman -Si package
Install a package (with appropriate file extension) on the local file systemsudo dpkg -i package.debsudo dnf install package.rpmpacman -S package
Remove / uninstall a packagesudo apt remove packagesudo dnf erase packagepacman -R package
List installed packagesdpkg -l / apt list --installedrpm -qa / dnf list installedpacman -Q
Remove with configsapt purge pkgdnf remove pkgpacman -Rns pkg
Dependenciesapt-cache depends pkgdnf deplist pkgpacman -Qi pkg
Find package owning filedpkg -S /path/filerpm -qf /path/filepacman -Qo /path/file
Verify packagedebsums pkg (if installed)rpm -V pkgpacman -Qk pkg
Full upgradeapt full-upgradednf upgrade --refreshpacman -Syu

Security Tools

These commands are used to manage and configure Linux security frameworks like SELinux and AppArmor. They help enforce access controls, monitor security contexts, define policies, and switch between enforcement and permissive modes.

CommandDescription
getenforceShow current SELinux mode (enforcing, permissive, disabled).
setenforce 0 1Set SELinux mode: 0 = permissive, 1 = enforcing.
getsebool -aList SELinux booleans and their states.
setsebool -P var on offSet SELinux boolean var on or off, persistent across reboots.
chcon -t type fileChange SELinux security context of a file.
restorecon -Rv pathRestore SELinux context defaults on a path.
semanage fcontext -a -t type pathDefine default SELinux context rules.
audit2allowSuggest SELinux policy changes from audit logs.
aa-statusShow AppArmor profile status.
aa-enforce profilePut an AppArmor profile in enforce mode.
aa-complain profilePut an AppArmor profile in complain mode (log only).

Containers

Working with containers is central to modern DevOps and cloud-native environments. These commands let you build and run Docker images, manage active containers, and interact with Kubernetes pods for orchestration.

CommandDescription
docker run -it imageRun a container interactively.
docker build -t name .Build an image from a Dockerfile.
docker psList running containers.
docker exec -it id bashGet a shell inside a running container.
docker stop idStop a container.
docker rmi imageRemove an image.
kubectl get podsList Kubernetes pods.
kubectl describe pod nameShow pod details.

Scripting and Automation

These commands cover shell loops, conditionals, scheduling tasks, and version control with Git to automate workflows.

CommandDescription
for var in list; do ...; doneLoop through a list of values.
while condition; do ...; doneLoop while a condition is true.
if [ condition ]; then ...; fiConditional execution.
case $var in pattern) ... ;; esacMulti-branch conditional.
read varRead input into a variable.
echo $varOutput variable contents.
$?Show exit status of last command.
cron / crontab -eSchedule recurring tasks.
at timeSchedule a one-time task.
git clone urlClone a Git repo.
git add fileStage file changes.
git commit -m "msg"Commit changes.
git pushPush commits to remote repo.
git checkout branchSwitch to a branch.

vi Editor Basics

The vi editor is a powerful text editor available on all Unix-like systems. These commands cover basic navigation, editing, and saving within vi.

CommandDescription
vi fileOpen file in vi editor.
iSwitch to insert mode.
EscReturn to command mode.
:wSave changes.
:qQuit vi.
:q!Quit without saving.
:wqSave and quit.
ddDelete the current line.
yyCopy (yank) the current line.
pPaste copied or deleted text.
/patternSearch for pattern.
nRepeat last search.

Linux Commands Cheat Sheet Conclusion

Learning basic Linux commands is a solid first step toward building a career in IT and cyber security. You’re now ready to practice these skills on any Linux distribution you prefer, whether that’s Ubuntu, Fedora, or security-focused systems like Kali Linux and Parrot OS. Don’t forget to grab our handy Unix Commands Cheat Sheet to keep your skills sharp.

To continue your journey, explore our Complete Linux Training Courses Bundle. This all-in-one bundle takes you far beyond the basics, covering Linux administration, shell scripting, system security, and much more, giving you a well-rounded foundation for both IT operations and cyber security.

And if you’re looking to expand even further, StationX also offers CompTIA Linux+ exam vouchers for those interested in certification, as well as our industry-leading Master’s Program, which provides 30,000+ cybersecurity courses & labs with guided learning, certifications, and full career support.

Frequently Asked Questions

Guarantee Your Cyber Security Career with the StationX Master’s Program!

Get real work experience and a job guarantee in the StationX Master’s Program. Dive into tailored training, mentorship, and community support that accelerates your career.

  • Job Guarantee & Real Work Experience: Launch your cybersecurity career with guaranteed placement and hands-on experience within our Master’s Program.
  • 30,000+ Courses and Labs: Hands-on, comprehensive training covering all the skills you need to excel in any role in the field.
  • Pass Certification Exams: Resources and exam simulations that help you succeed with confidence.
  • Mentorship and Career Coaching: Personalized advice, resume help, and interview coaching to boost your career.
  • Community Access: Engage with a thriving community of peers and professionals for ongoing support.
  • Advanced Training for Real-World Skills: Courses and simulations designed for real job scenarios.
  • Exclusive Events and Networking: Join events and exclusive networking opportunities to expand your connections.

TAKE THE NEXT STEP IN YOUR CAREER TODAY!

  • Nathan House

    Nathan House is the founder and CEO of StationX. He has over 25 years of experience in cyber security, where he has advised some of the largest companies in the world. Nathan is the author of the popular "The Complete Cyber Security Course", which has been taken by over half a million students in 195 countries. He is the winner of the AI "Cyber Security Educator of the Year 2020" award and finalist for Influencer of the year 2022.

  • FRANKLIN AMBOMU says:

    Thank you sir

  • Nick says:

    Awesome thanks so much, cant wait to play around with these and learn so many new ones too :)

  • Abdul Latheef says:

    Excellent, thanks for sharing, superb..

  • Luis Reales says:

    Thank you so much, awesome work!

  • Ankit Kanojiya says:

    how we can download?

  • Be yur Fut Ur says:

    This website is a gem! A lot of info and you’ll learn every day something new!

  • MnNice507 says:

    Can I bypass bitlocker recovery via Linux?

  • Cyril says:

    so much information on this page ….loaded and very useful. Bless you all!

  • >

    StationX Accelerator Pro

    Enter your name and email below, and we’ll swiftly get you all the exciting details about our exclusive StationX Accelerator Pro Program. Stay tuned for more!

    StationX Accelerator Premium

    Enter your name and email below, and we’ll swiftly get you all the exciting details about our exclusive StationX Accelerator Premium Program. Stay tuned for more!

    StationX Master's Program

    Enter your name and email below, and we’ll swiftly get you all the exciting details about our exclusive StationX Master’s Program. Stay tuned for more!