Linux Command-Line Cheat Sheet

·

Linux Command Line Cheat Sheet

Linux is one of the most widely used operating systems in the world, and with such a high level of usage, it has essentially become one of the most important tools for any IT professional to have. A lot of Linux’s power resides in the terminal emulator.

In this article, I will share a Linux command-line cheat sheet to help you get started with using Linux. The commands mentioned below will serve as the foundation for working across the different distributions and families of Linux, as there are many of them.

Get Started

I will start by explaining how the Linux terminal works. This is an oversimplified explanation to give you a basic understanding. The terminal is software that you use to communicate with the operating system. Anything you type into it is passed to a shell, which interprets the command and, when appropriate, executes the corresponding program.

For starters, one question that has plagued humanity for centuries: whoami.

whoami

After running this command, it will print your username, allowing you to know which user you are currently logged in as. It is also quite often used by attackers after they breach a system to determine which user they are operating as.

File Management

Let’s create a file. There are multiple ways to create a file, but one of the most common is the touch command. It is used to create an empty file or update the timestamps of an existing file.

If you want to create a file with some content, you can use the echo command. This command is used to print something to the screen, but you can redirect that output (hey, save this) to a file using >. For appending content, which means adding content to the end of an existing file, you can use >>.

Be careful, though: the single > symbol will overwrite the contents of a file if it already exists.

touch test.txt
echo "Konnichiwa, World" > test.txt

Now that you have created a file, you might want to delete it. For that, you can use the rm command. It can be used to delete both files and folders.

rm test.txt

Let’s make a folder. To create a folder, you can use the mkdir command. This command accepts the name of the folder you want to create and will create it for you.

mkdir mynicefolder

To delete the folder you just created, you can use the rmdir command. It is used to delete empty folders.

If you have multiple files inside the folder, you will need to use the previous command with a cute little flag. A flag is a special option that you use to modify how a command behaves, allowing it to perform additional functions, such as deleting a non-empty folder.

For this, you can use rm -r. The -r flag stands for recursive, which tells the command to delete the folder and everything inside it.

rmdir mynicefolder
rm -rf mynicefolder

There are two more useful commands you should know, the copy and move commands.

For copying files, you can use the cp command. It follows the syntax <file to copy> <location to copy to>.

cp test.txt /home/skipper

For moving files, you can use the mv command. It follows the same syntax as the cp command, but instead of creating a copy, it moves the file entirely to a new location.

mv test.txt /home/purpleshonen

Navigation

Before we learn to move across different directories or folders, we need to know which directory you are currently in, and for that, there is a very useful command called pwd. It stands for print working directory, and it will print the directory you are currently working in.

pwd

Linux filesystems follow a tree-like structure, and you can imagine it as an upside-down tree. You are moving towards or up the tree towards the root, and when you move to a different directory, for example /home/skipper, you are moving away and downward from the root. This will make more sense with the infographic below, and the root directory is / in Linux, unlike in Windows, where you typically have different drive letters such as C:\.

Before you can navigate around and change directories, you need to learn about the ls command, which is used for listing files and directories. If you don’t provide any <location>, it’s gonna print out the files and directories in the current directory.

ls

In order to move around, you use the cd command, which stands for change directory. In order to go back to the previous directory, you can use .., which acts somewhat like the back button in a file explorer and moves you one directory up. To change directory to another folder, you need to put the name of the directory you are trying to move into.

cd ..
cd mynicefolder

As I mentioned above, Linux has a tree-like hierarchy. It also has two types of paths, and each works to achieve the same goal but works differently. These two are absolute paths and relative paths. I will explain these in a little more detail.

An absolute path starts from the root. An example of it would be /home/skipper/test.txt; this is an absolute path.

A relative path starts from the current working directory. For example, if you are currently in /home/skipper, you can use ../purpleshonen/ to move to the purpleshonen directory under /home. This is considered a relative path because it is resolved based on your current working directory.

I hope that makes sense. It’s important to understand, as it is crucial when moving around to different directories or using any command that requires a path.

Now that you have a good understanding of how to navigate around, and if you want to go to your home directory from any directory, then you can use the ~ symbol, which represents your home directory.

cd ~/

Permissions

Linux uses discretionary access control (DAC) for its traditional file permission system, which means the owner of a file or folder can decide what permissions different users have, subject to the system’s permission rules. In Linux, to see the permissions of different files, you can use the -l flag with the ls command. It’s gonna show the permissions for the owner, then the permissions for the group, and lastly the permissions for others.

In order to change the permissions, we use the chmod command, which is short for change mode, aka changing permissions. In the example below, you will see how we can make a file or script executable by using the +x option and then the name of the filename.

chmod +x test.bin

To remove the execute permission, you can change the +x to -x. Now the file will no longer have the execute permission that was previously added.

chmod -x test.bin

There are multiple options you can use aside from the execute permission. For read permission, you can use the +r option, and for write permission, you can use +w. Being able to manipulate permissions is a very crucial part of the Linux system. You should familiarize yourself with chmod commands, as it’s a very useful yet powerful command.

Networking

Networking is also a very crucial part of Linux, and there are a few important commands you should be familiar with. Some of the important ones start with the ip command. This command is a very powerful utility that is used to manage networking, IP addresses, routing tables, and network interfaces.

To view the IP addresses configured on your system, you can use the address show argument to list and view them.

ip address show

If you specifically want to view IPv4 addresses, you can use:

ip -4 address show

In order to view the network interfaces available or check their state, you can use the link show argument, which will list and show all the available interfaces on your system.

ip link show

These were some of the common commands that would come in handy when using the Linux operating system, and below I will add a table of the most common commands used in everyday use that would be a valuable asset to learn.

Before I end this article, I have one last command.

If you don’t know what a specific command does or you want to learn more about any of the commands covered, then you can use the man <command name> command, which will open up a manual that you can read to further understand how to use that specific command and what other options it supports.

man <command>

Cheat Sheet

Below are some of the most useful Linux commands that you should familiarize yourself with. The commands covered above are intentionally left out, so this section can serve as a quick reference for commands that you haven’t seen yet.

Files & Directories

CommandWhat it doesExample
catDisplays the contents of a filecat test.txt
lessLets you read a file one screen at a timeless test.txt
headDisplays the beginning of a filehead test.txt
tailDisplays the end of a filetail test.txt
fileDetermines the type of a filefile test.txt
findSearches for files and directoriesfind /home -name "test.txt"
locateQuickly searches for files by namelocate test.txt
treeDisplays directories in a tree structuretree /home
lnCreates links to filesln -s /path/to/file link
statDisplays detailed file informationstat test.txt

Text Processing

CommandWhat it doesExample
grepSearches for text inside files or command outputgrep "password" file.txt
sortSorts lines of textsort names.txt
uniqRemoves or identifies repeated linesuniq names.txt
cutExtracts sections from lines of textcut -d: -f1 /etc/passwd
wcCounts lines, words, and characterswc -l file.txt
trTranslates or removes characterstr 'a-z' 'A-Z'
sedSearches and transforms textsed 's/foo/bar/g' file.txt
awkProcesses and analyzes structured textawk '{print $1}' file.txt
diffCompares two filesdiff file1.txt file2.txt

Processes & System

CommandWhat it doesExample
psDisplays running processesps aux
topDisplays running processes and system activitytop
htopInteractive process viewerhtop
killSends a signal to a processkill 1234
pkillSends a signal to processes by namepkill firefox
jobsShows jobs running in the current shelljobs
bgSends a stopped job to the backgroundbg
fgBrings a background job to the foregroundfg
freeDisplays memory usagefree -h
dfDisplays filesystem disk usagedf -h
duDisplays the size of files and directoriesdu -sh /home
uptimeShows how long the system has been runninguptime
unameDisplays system informationuname -a
hostnameDisplays or changes the system hostnamehostname
lsblkLists block devices and storage driveslsblk
mountMounts a filesystemmount /dev/sdb1 /mnt
umountUnmounts a filesystemumount /mnt

Networking

CommandWhat it doesExample
pingTests network connectivityping 8.8.8.8
ssDisplays network sockets and connectionsss -tuln
curlTransfers data from or to a URLcurl https://example.com
wgetDownloads files from the webwget https://example.com/file.zip
digPerforms DNS lookupsdig example.com
nslookupPerforms DNS queriesnslookup example.com
tracerouteShows the route packets take to a destinationtraceroute example.com
hostnamectlDisplays or manages hostname informationhostnamectl
arpDisplays or modifies ARP informationarp -a

Users & Permissions

CommandWhat it doesExample
idDisplays user and group informationid
groupsShows the groups a user belongs togroups
sudoExecutes a command with elevated privilegessudo command
suSwitches to another usersu username
passwdChanges a user’s passwordpasswd
chownChanges the owner of a filesudo chown user file.txt
chgrpChanges the group ownership of a filesudo chgrp developers file.txt
umaskDisplays or changes the default permission maskumask

Archives & Compression

CommandWhat it doesExample
tarCreates or extracts archivestar -cf archive.tar files/
gzipCompresses files using gzipgzip file.txt
gunzipDecompresses gzip filesgunzip file.txt.gz
zipCreates ZIP archiveszip archive.zip file.txt
unzipExtracts ZIP archivesunzip archive.zip

Package Management

Package management commands depend on the Linux distribution you are using.

CommandWhat it doesExample
aptManages packages on Debian-based distributionssudo apt install nmap
dnfManages packages on Fedora-based distributionssudo dnf install nmap
pacmanManages packages on Arch-based distributionssudo pacman -S nmap
rpmWorks with RPM packagesrpm -qa
dpkgWorks with Debian packagesdpkg -l

Services & Logs

CommandWhat it doesExample
systemctlManages systemd servicessystemctl status sshd
journalctlReads systemd logsjournalctl -u sshd
dmesgDisplays kernel messagesdmesg
serviceManages services on systems that support itservice ssh status

Shell & Environment

CommandWhat it doesExample
clearClears the terminalclear
historyDisplays previously executed commandshistory
aliasCreates command shortcutsalias ll='ls -la'
envDisplays environment variablesenv
printenvPrints environment variablesprintenv HOME
exportSets an environment variableexport NAME=value
whichShows the location of a commandwhich python
whereisLocates binaries, source files, and manualswhereis python
typeShows how the shell interprets a commandtype cd
echo $PATHDisplays the command search pathecho $PATH

Useful Shortcuts

ShortcutWhat it does
Ctrl + CStops the currently running command
Ctrl + DExits the current shell or sends EOF
Ctrl + LClears the terminal screen
Ctrl + ZSuspends the current process
Ctrl + RSearches through command history
TabAutocompletes commands, paths, and filenames
↑ / ↓Moves through command history
!!Repeats the previous command
&&Runs the next command only if the previous command succeeds
|Pipes the output of one command into another
>Redirects output and overwrites a file
>>Redirects output and appends to a file
2>Redirects standard error
2>&1Redirects standard error to standard output

This is by no means an exhaustive list of Linux commands. Linux has thousands of commands and utilities, and many of them are designed for very specific tasks. However, learning these commands will give you a much stronger foundation for working with the Linux command line.