Linux Cheat Sheet

When you start learning something new, it’s normal that you won’t know all commands by heart. That comes much later after hours of practice. Cheat sheets comes in handy in those times when you are still working on memorising commands. 

System

unameDisplays  Linux system information
uname -rDisplays  kernel release information
uptimeDisplays how long the system has been running including load average
hostnameShows the system hostname
hostname -iDisplays the IP address of the system
last rebootShows system reboot history
dateDisplays current system date and time
timedatectlQuery and change the System clock
calDisplays the current calendar month and day
wDisplays currently  logged in users in the system
whoamiDisplays who you are logged in as
finger usernameDisplays information about the user

General

suSwitches user.
- <user>Switches to user.
-Switches to root.
manHelp on commands.
<section>Section numbers: 1. Programs, 2. System calls, 3. Library calls, 4. Special files, 5. File formats, 7. Miscellaneous, 8. System administration commands
echoPrints passed text.
-nDoes not add newline at the end.
-eEnables interpretation of backslashed letters.
xargs <cmd>Passes output from one command to arguments of another:
'echo -a | xargs ls'
-tEchoes the command before executing it.
-pEchoes command and asks for confirmation before execution.
-0Input items are separated by null character instead of space.
tee <file>Sends output of a program to specified file and to standard output:
'<cmd_1> | tee out_1.txt | <cmd_2>'
/dev/ttySends output to terminal and to standard output
exprEvaluates passed expression.
1 + 1Prints '2'.
bcEvaluates input. It's basically a calculator, but also provides some control commands.
echo 1 + 1 | bcPrints '2'.
echo "scale=5;3/4" | bcPrints '.75000'.
shRuns command interpreter (shell). Can run a script even if not executable.
-c '<commands>'Starts new non-interactive shell and reads commands from arguments instead of 'stdin'.
To append lines to system configuration file run:
'sudo sh -c 'echo "<text>" >> <file>''
bashRuns bash command interpreter (shell).
-cReads commands from arguments instead of 'stdin'.
-n <script>Checks script for errors.
-xPrints commands before execution. Useful for debugging.
gccGnu C compiler. Run 'g++' for C++ code.
-wSupresses warnings (Only prints errors).
-WallAll warnings.
-gCompile for debugging.
-std=<std>Sets the standard. Suported standards for C are:
'c90', 'gnu90', 'c99', 'gnu99', 'c11' and 'gnu11'.
Suported standarts for C++ are:
'c++98', 'gnu++98', 'c++11' and 'gnu++11'.
'gnu90' and 'gnu++98' are the default options.
-O<level>Optimization level. '0': Reduce compilation time (default), '1-3': - Level of optimization, 's' - Optimize for size, 'g' - Optimize debugging experience.
run-parts <dir>Runs all scripts or programs in a directory.
dateTells and sets date and time.
-s <string>Sets date.
+%T -s "10:13:13"Sets time.
timedatectlControls the system time and date.
set-timezone CETSets timezone.
calCalendar
xclipCopies to clipboard.
mkfifo <pipe>Creates named pipe during that shell session.
mkisofsCreates a DVD/CD image.
genisoimageCreates a DVD/CD image (Debian).
cdrecordWrites to a CD/DVD.
acpiChecks battery.
fdisk -l (sudo)Shows partitions.
shutdownCloses down the system at a given time.
nowTakes you to the single user mode.
-h nowBegins the shutdown procedure, same as 'halt' and 'poweroff'.
-h 11:50At 11:50.
-r nowSame as 'reboot'.
makeUtility that maintains groups of programs.
-qDoesn't run any commands, just returns '0' exit code if everything is up to date or non-zero otherwise.
-BUnconditionally makes all targets.

Files

ls
-dList directory names instead of contents
-SSort by size
-tSort by time
-1One file per line
./*Ls one level deep
-iGet inode number of file (file id). Use 'sudo find / -inum <number>' to find all links that point to same file.
cp
-iInteractive (Prompts before overwrite)
-vVerbose (Explains what is being done)
-RCopy directories recursively
-pPreserve mode, ownership and timestamps
--preserve=allAlso preserves context, links and xattr
rm
-iInteractive (Prompts before every removal)
-vVerbose (Explains what is being done)
-fForce remove (Does not prompt, useful if 'rm' is aliased with '-i')
-RRemoves directories and their content recursively
mkdir
-pMake parents if needed
lnMakes links to the files
-s <file> <link>Makes symbolic link. If you want to use relative paths you must be in links directory !!!!!!!!!!!!!!!!!!!!!!
df
-hDisplays humanly readable free disk space
du
-s <dir>Directory size
mcMidnight commander
Alt oOpen parent dir in another panel
Ctrl oSwitch to bash
find <dir>
-name <file>Search by name
-regex <regex>Use regex for name search
-notInsert before other options to negate
-maxdepth <levels>Descend only to levels deep
-samefile <file>Find all hard links of a file
-xdevDon't descend directories on other filesystems
-inum <inum>Find files with the inode number
-type <f|d|b|...>Find files of type
-deleteDelete found files
-exec <cmd> {} \;Find files and execute command for every found file. '{}' is replaced with filename
-exec <cmd> {} +Find files and execute command with all filenames in place of '{}'
-atime +/-nFind files that were last accessed less or more than n days.
-print0 | xargs -0 <cmd>Sends found files to a command as parameters. Uses 'NUL' character as separator, necessary for filenames with spaces
locate <regex>Similar as 'find' but using index
-iIgnore case
--regexInterprets all patterns as extended regex
-0 | xargs -0 <cmd>Sends found files to a command as parameters.
updatedb (sudo)Update locate index
md5sumPrints md5 sum hash of a file
readRead single line from standard input
-n 1Print after reading one character
-sDo not echo input coming from terminal
shredSecurely remove files
fileDetermine file's type
treeLs in a tree-like (hierarchical) format
installCopy files and set attributes
gpgDecrypt file with password
-cEncrypt
mktempCreate a temporary file or directory in '/tmp' and returns it's name.
rename
s/<from>/<to> <files>Renames multiple files using 'sed' syntax
rsyncA fast, versatile, remote (and local) file-copying tool
-Hbaz -e ssh'<src_dir> <user>@<host>:<dest_dir>' - Backs up the 'src-dir': '-H' preserves hard links, '-b' renames preexisting destination files (back up), '-a' preserve everything except hard links and '-z' compresses.
cmpCompares two files, similar to diff but also for binaries
statDisplays files status
-c%XTime of last modification of the file
readlink
-fFollow link recursively and print files path
xdg-openOpen file with default application for the file type
dialogDisplay dialog box from shell script
watchExecute command periodically

Archives

dtrx
<archive>Universal archive extractor
tar
xvzf <file>.tar.gz (.tgz)Decompress and detar
xvjf <file>.tar.bz2Decompress and detar
-cf <archive>.tar <files>Compress
unzip
\*.zipBackslash is necessary so that bash doesn't expand the '*'
-d <dir>Extract into directory (create if doesn't exist)
zip
-r <archive> <dir>Compress whole directory recursively.
-g <archive> <files>Add files to existing archive (grow).
unrar
eExtract files from rar archive
zcatCats gziped file

Packages

dpkgLow level package manager for Debian.
-lLists installed packages.
-i <package> (sudo)Installs package from a package file.
apt-getAdvanced Package Tool built on top of 'dpkg'. New command called simply 'apt' is also available. It merges the functionalities of 'apt-get' and 'apt-cache'.
updateUpdates local list of existing packages.
-u dist-upgradeUpgrades by intelligently handling changing dependencies with new versions of packages. To regularly update put this line in 'crontab':
'apt-get update && apt-get -u dist-upgrade'.
upgradeSame as dist-upgrade, but will not remove installed packages or install new ones.
install <package>Also updates single package.
remove <package>Removes package but leaves its configurations.
remove apt-listchangesUseful when Debian can't find a package.
purge <package>Removes package and its configurations. Run 'apt-get autoremove' after to remove all dependencies that are not needed anymore.
autoremoveRemoves unneeded packages.
source <package>Downloads code.
build-dep <package>Installs the build dependencies.
--yesAnswers with 'yes' to most questions (Except the ones that can have potentially harmful consequences).
--force-yesAnswers 'yes' to all questions (Not recommended).
apt-cacheQueries the APT's internal database.
search <keyword>Searches packages like 'apropos', but globally.
show <package>Shows package info like version, dependencies, etc.
showpkg <package>Similar, but also shows the packages that depend on the searched package (reverse dependencies).
policy <package>Shows installed and remote version.
apt-fileAPT package searching utility.
search <file>Search in which package a file is included.
updateUpdates local list of package contents.
aptitudeEnables package browsing (skin for apt-get).
search '~i!~M'Lists installed packages that were not installed as a dependency, with short description of each.
search <package>Package search.

winetricksInstalls wine applications.
update-alternativesMaintains symbolic links determining default commands.
unattended-upgradeAutomatic installation of security upgrades.

Hardware

dmesgDisplays bootup messages
cat /proc/cpuinfoDisplays more information about CPU e.g model, model name, cores, vendor id
cat /proc/meminfoDisplays more information about hardware memory e.g. Total and Free memory
lshwDisplays information about system's hardware configuration
lsblkDisplays block devices related information
free -mDisplays free and used memory in the system (-m flag indicates memory in MB)
lspci -tvDisplays PCI devices in a tree-like diagram
lsusb -tvDisplays USB devices in a tree-like diagram
dmidecodeDisplays hardware information from the BIOS
hdparm -i /dev/xdaDisplays information about disk data
hdparm -tT /dev/xda <:code>Conducts a read speed test on device xda
badblocks -s /dev/xdaTests  for unreadable blocks on disk

Users

idDisplays the details of the active user e.g. uid, gid, and groups
lastShows the last logins in the system
whoShows who is logged in to the system
groupadd "admin"Adds the group 'admin'
adduser "Sam"Adds user Sam
userdel "Sam"Deletes user Sam
usermodUsed for changing / modifying user information

File Commands

ls -alLists files - both regular &  hidden files and their permissions as well.
pwdDisplays the current directory file path
mkdir 'directory_name'Creates a new directory
rm file_name Removes a file
rm -f filenameForcefully removes a file
rm -r directory_nameRemoves a directory recursively
rm -rf directory_nameRemoves a directory forcefully and recursively
cp file1 file2Copies the contents of file1 to file2
cp -r dir1 dir2Recursively Copies dir1 to dir2. dir2 is created if it does not exist
mv file1 file2Renames file1 to file2
ln -s /path/to/file_name   link_nameCreates a symbolic link to file_name
touch file_nameCreates a new file
cat > file_namePlaces standard input into a file
more file_nameOutputs the contents of a file
head file_nameDisplays the first 10 lines of a file
tail file_nameDisplays the last 10 lines of a file
gpg -c file_nameEncrypts a file
gpg file_name.gpgDecrypts a file
wcPrints the number of bytes, words and lines in a file
xargsExecutes commands from standard input

Process Related

psDisplay currently active processes
ps aux | grep 'telnet'Searches for the id of the process 'telnet'
pmapDisplays memory map of processes
top Displays all running processes
kill pidTerminates process with a given pid
killall procKills / Terminates all processes named proc
pkill process-nameSends a signal to a process with its name
bgResumes suspended jobs in the background
fgBrings suspended jobs to the foreground
fg njob n to the foreground
lsofLists files that are open by processes
renice 19 PIDmakes a process run with very low priority
pgrep firefoxfind Firefox process ID
pstreevisualizing processes in tree model

File Permission

chmod octal filenameChange file permissions of the file to octal
Example
chmod 777 /data/test.cSet rwx permissions to owner, group and everyone (everyone else who has access to the server)
chmod 755 /data/test.cSet rwx to the owner and r_x to group and everyone
chmod 766 /data/test.cSets rwx for owner, rw for group and everyone
chown owner user-fileChange ownership of the file
chown owner-user:owner-group file_name Change owner and group owner of the file
chown owner-user:owner-group directoryChange owner and group owner of the directory

Network

ip addr showDisplays IP addresses and all the network interfaces
ip address add 192.168.0.1/24 dev eth0Assigns IP address 192.168.0.1 to interface eth0
ifconfig Displays IP addresses of all network interfaces
ping  hostping command sends an ICMP echo request to establish a connection to server / PC
whois domainRetrieves more information about a domain name
dig domainRetrieves DNS information about the domain
dig -x host Performs reverse lookup on a domain
host google.com Performs an IP lookup for the domain name
hostname -iDisplays local IP address
wget file_nameDownloads a file from an online source
netstat -pnltuDisplays all active listening ports

Compression/Archives

tar -cf home.tar home<:code>Creates archive file called 'home.tar' from file 'home'
tar -xf files.tarExtract archive file 'files.tar'
tar -zcvf home.tar.gz source-folderCreates gzipped tar archive file from the source folder
gzip fileCompression a file with .gz extension

Install Packages

rpm -i pkg_name.rpmInstall an rpm package
rpm -e pkg_nameRemoves an rpm package
dnf install pkg_nameInstall package using dnf utility

Install Source (Compilation)

./configureChecks your system for the required software needed to build the program. It will build the Makefile containing the instructions required to effectively build the project
makeIt reads the Makefile to compile the program with the required operations. The process may take some time, depending on your system and the size of the program
make installThe command installs the binaries in the default/modified paths after the compilation

Search

grep 'pattern' filesSearch for a given pattern in files
grep -r pattern dirSearch recursively for a pattern in a given directory
locate fileFind all instances of the file
find /home/ -name "index" Find file names that begin with 'index' in /home folder
find /home -size +10000kFind files greater than 10000k in the home folder

Login

ssh user@hostSecurely connect to host as user
ssh -p port_number user@host Securely connect to host using a specified port
ssh hostSecurely connect to the system via SSH default port 22
telnet hostConnect to host via telnet default port 23

File Transfer

scp file1.txt server2/tmpSecurely copy file1.txt to server2 in /tmp directory
rsync -a /home/apps  /backup/Synchronize contents in /home/apps directory with /backup  directory

Disk Usage

df  -hDisplays free space on mounted systems
df  -i Displays free inodes on filesystems
fdisk  -lShows disk partitions, sizes, and types
du  -shDisplays disk usage in the current directory in a human-readable format
findmntDisplays target mount point for all filesystems
mount device-path mount-pointMount a device

Directory Traverse

cd ..Move up one level in the directory tree structure
cdChange directory to $HOME directory
cd /testChange directory to /test directory

 

PDF version: Linux Cheat Sheet


The above list is only scratching the surface of Linux commands. There is far more you can do in the terminal than we could ever hope to fit on one page. Plus many commands change depending on your Linux-based operating system or require installing additional programs. If you noticed that somethings is wrong or if there is something we can improve (or add to the list), leave a comment!

August 16, 2019
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
© HAKIN9 MEDIA SP. Z O.O. SP. K. 2013