Show Menu
Cheatography

Linux Commands Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Quick basic commands

cd (Example: cd Desktop)
change directory, case sensitive
cd
home directory
.
this directory
cd ..
go up one directory
cd -
change dir to previous working dir
pwd
print working directory
ls
list contents, -a all, -h human readable
ll
LL list direct­ories with RW permis­sions
la
LA list all including hidden
sudo
super user privileges
mkdir <di­rna­me> <di­rna­me2>
create direct­ories
cp <path and locati­ons> .
copy contents to current directory, cp by itself will overwrite files silently
mv <it­em1> <it­em2> directory
move file(s) to location
rm -i <it­em>
delete file, -i intera­ctive confir­mation
alias
lists alias commands
alert <"me­ssa­ge">
sends a message to notifi­cations
> emptyD­OC.txt
make an empty text file
>
standard out to .txt (will overwrite)
>>
append standard out .txt will (not overwrite)
ls -la /usr/bin > ls-out­put.txt
will print the directory contents to a text file
&>
will include output and errors

apt

apt list
| grep Type a word to highlight in red
apt search
| grep searchword
apt install
app name
apt remove
app name
apt update
apt upgrade

Permis­sions

id
Display user idenity
chmod
Change a files mode
umask
Set the default file permis­sions
su
Run a shell as another user
sudo
Execute a command as another user
chown
Change a file's owner
chgrp
Change a file's group ownership
passwd
Change a user's password

Reading, Writing, Executing -rw-r--r--

Example
-rw-r--r--
-
col1. Regular file
d
col1. Directory
l
col1. A symbolic link. Dummy values.
c
col1. A charcater special file. Modem
b
col1. A block special file. Ex. CD, HDD.
r
Read only
w
Write
x
Executable

iptables (firewall)

iptables -h
list commands
--list
list the rule in a chain or all chains
--verbose or -v
details
--line­-nu­mbers
print line numbers when listing
--version or -V
version number
--list­-rules or -S
list rules
--numeric or -n
numeric output of addresses and ports

Permission Attribute Examples

-rwx------
read, write, execute by file's owner only
-rw-------
read and write by owner only
-rw-r--r--
read and write owner, read group, read world
-rwxr-xr-x
read, write, execute owner. read and execute everyone else.
lrwxrwxrwx
A symbolic link with dummy permis­sions
drwxr-x---
Directory. read, write, execute owner. Read and execute group.

Changing passwords

passwd [user]
with sudo you can change a user password
passwd
change your password

chown

chown [owner­][:­[gr­oup]] file..
syntax use
bob
change ownership from current to bob
bob:users
change file ownership to bob and group to users
:admins
change group owner to admins, the owner is unchanged
bob:
change the current owner to bob and change the group to the login group for bob

text editors

gedit
GUI (installed in Ubuntu)
kedit
KDE default
kate
sudo apt install kate
nano
command line based (installed in Ubuntu)
vi or vim
vi IMproved (installed in Ubuntu)
emacs
sudo apt install emacs-gtk

text editing basics

make a backup before editing
cp <fi­len­ame> <fi­len­ame.ba­k>
nano <fi­len­ame>
load a text in nano

nano text editor

^X
to quit nano, ^ mean CTRL
^O CTRL-O
save the file

vi or vim text editor

vi
start vim
vi newdoc.txt
create a blank text doc in vi from command line
:q
quit
:q!
quit without saving
vi starts in command mode
press i to go to insert text mode
press ESC to exit insert mode
exit insert mode with ESC
:w
save the file, or write to file
double tap ESC if you don't know where you are in vi
Navi­gating Command Mode
H or left arrow
left one character
J or down arrow
down one line
K or up arrow
up one line
L or right arrow
right one character
0 (zero)
go to the beginning of the current line
SHIFT-6 (^)
to the first non whitespace character on the current line
SHIFT-4 ($)
to the end on the current line
W
to the beginning of the next word, or punctu­ation characters
SHIFT-W (W)
to the beginning of the next word, ignore punctu­ation characters
B
to the beginning of the previous word or character
SHIFT B (B)
to the beginning of the previous word or character, ignoring punctu­ation
CTRL-F or page down
down on page
CTRL-B or page up
up one page
number­-SH­IFT-G
to the line number, example 1G moves to the first line of the file
SHIFT-G
to the last line of the file
Cutting, Copying, Pasting Text
DELETE TEXT aka CUT TEXT
x
delete the current character
3x
delete the current character and the 2 after it
dd
delete the current line
5dd
delete the current line and the next 4 lines
dW
delete from the current cursor position to the beginning of the next word
d$
delete from the current cursor position to the end of the line
d0
delete from the current cursor position to the beginning of the line
d^
delete from the current cursor location to the first non whitespace character line
dG
from the current line to the end of the file
d20g
from the current line to the 20th line of the file
COPY­ING
yy
y stands for yank which is copy, yy copies the current line
5yy
copies the current line and the next 4 lines
yW
from the cursor location to the beginning of the next word
y$
from the cursor location to the end of the current line
y0
from the current cursor location to the beginning of the line
y^
from the current cursor location to the first non whitespace character in line
yG
from the current line to the end of the file
y20G
from the current line to the 20th line of the file
PAST­ING
p
pastes the current copied text below the current line
P
pastes the copied text above the current line
Join lines
J
vi has the ability to do search and replace
maybe I will add a cheat sheet for this later
/searc­htext
searches vi
:%s/Li­ne/­line/g
will search and replace Line with line globally
EDIT MULTIPLE FILES
vi file1 file2 file3
:n
switch to the next file
:N
switch to the previous file
:buffers
lists open files
:buffers 2
switch to buffer file 2
:e
open another file from vi. example :e filena­me.txt
:r
copy an entire file to the vi session. example :r myfile.txt

Networking commands

ping
send en ICMP echo request to network hosts
traceroute
print the route packets trace to a network host
netstat
print the network connec­tions, routing tables, interface stats, masquerade connec­tions, and multi cast member­ships
ftp
file transfer program
lftp
an improved ftp
wget
non intera­ctive network downloader
ssh
openSSH SSH client (remote login)
scp
secure copy (remote copy program)
sftp
secure ftp
 

Technical commands

cat (brings files together, uses input)
CTRL-D to quit, tell cat EOF
cat > somete­xt.txt; this is some text to be saved
a simple way to add text to a text file
cat somete­xt.txt
to read the file with cat
|
pipe connects input to output
ls /bin /usr/bin |sort | less
example sort 2 dirs binaries
sort
alphab­etize a list
uniq
used with sort, removes duplicates
grep
pattern finding
head
checks the first 10 lines of a file. -n # (to adjust #)
tail
checks the last 10 lines of a file. -n#
tail -f /var/l­og/­mes­sages
-f is a real time log file viewer switch­(CTRL-C to quit)
tee
for use with pipe
echo *D
display everything with a capital D
echo $((2+2))
command line calculator
echo "­$(c­al)­"
calendar
history
a list of all commands used
history: !88
!88 will use number 88 in history

USB checking

lsusb
list connected USB devices

dpkg

dpkg --list
list all installed packages
-r or --remove
remove a package
-P or --purge
--log=­<fi­len­ame>
log changes made
-i or --install <.deb file name>
install a deb file

chmod octal chart

octal
binary - filemode
0
000 ---
1
001 --x
2
010 -w-
3
011 -wx
4
100 r--
5
101 r-x
6
110 rw-
7
111 rwx
example setting octal 600
owner, group, world
 
binary seems somewhat irrelevant
chmod symbolic notation
u
user
g
group
o
others, world
a
all
example notation
u+x
add execute permission for the owner
u-x
remove execute permission from the owner
+x
add execute for everyone, same as a+x
o-rw
remove read and write for everyone but owner and group
u+x,go=rx
add excute for owner, group and world changed to read and execute

umask new file default permis­sions

umask
0022 ubuntu default
# position 0---
4000 sets program ownership to app
 
2000 sets group ownership for shared direct­ories
 
1000 set to a directory prevents files from being deleted in shared directory
the last three are octal permis­sions

system stuff

printenv | less
system inform­ation
printenv USER
views the contents of a variable, example USER contains your user name
set | less
display shell and enviro­nment variables
echo $HOME
echo can be used to view single variables
alias
lists all alias commands
[command]; alert [message]
to get a notifi­cation when a command is done(an alias in ubuntu)
below are some variables of interest
­­­­­­­­**
DISPLAY
the name of your display enviroment
EDITOR
the default text editor
SHELL
name of the shell running
HOME
path to home directory
LANG
keyboard language
OLD_PWD
the previous working directory
PAGER
the name of the program used for paging output. Usually is app less
PATH
a colon separated list of direct­ories that are searched when you enter the name of an executable program
PS1
prompt string 1, defines the contents of shell prompt
PWD
current working directory
TERM
the name of your terminal type
TZ
time zone
USER
your username

Storage Media command overview

mount
mount a file system
umount
un-mount a file system (pay attention to the spelling of the command Umount)
fdisk
partition table manipu­lator
fsck
check and repair a filesystem
fdformat
format a floppy disk
mkfs
make a filesystem
dd
write block-­ori­ented data directly to a device
geniso­image (mkisos)
create an ISO 9660 image file
wodim (cdrecord)
write data to an optical storage
md5sum
calculate MD5 checksum
LISTING DEVICES AND FILESY­STEMS
/etc/fstab
is a list of devices
mount
will view a list of mounted filesy­stems
ls /dev
list devices
/dev/fd*
floppy disks
/dev/hd*
hard drives
/dev/lp*
printers
/dev/sd*
SCSI disks
/dev/sr*
Optical drives CD/DVD readers and burners
sudo tail -f /var/l­og/­syslog
to see real time device changes in the system
MOVING DEV MOUNT LOCATI­ONS
sudo mkdir /mnt/flash
make a dir to mount flash drive
sudo mount /dev/sdb1 /mnt/flash
moves the location to the new one (use the proper device name before moving)
df
display disk space df -h for human readable

system startup stuff

/etc/p­rofile
a global config­uration script that applies to all users
~/.bas­h_p­rofile
a users personal startup file. can override the global config script
~/.bas­h_login
if ~/.bas­h_p­rofile is not found, bash attempts to read this one
~/.profile
if neither bash profile or login are found this is run. this is the default in Ubuntu
/etc/b­ash­/bashrc
a global config script that applies to all users
~/.bashrc
a users personal startup file
files that start with a period are hidden
is -a option when searching with ls

fdisk commands

sudo umount /dev/sdb1
unmount the partition
sudo fdisk /dev/sdb
mount the entire drive
fdsik commands
p
print partition tables
l
list known partition types
t
change a partitions system id
w
write partition changes
q
quit fdisk

creating a new filesystem with mkfs

sudo mkfs -t ext3 /dev/sdb1
make an ext3 filesystem on device sdb1 partition
sudo mkfs -t vfat /dev/sdb1
make a fat32 silesystem on device sdb1

testing and repairing filesy­stems with fsck

sudo fsck /dev/sdb1
checks the filesystem on sdb1 partition

Moving data directly to and from devices with dd

dd
raw copy tool (dd has 2 names, data definition and destroy disk)
dd if=inp­ut_file of=out­put­_file [bs=bl­ock­_size [count­=bl­ocks]]
syntax to dd raw copy
dd if=/de­v/sdb of=/de­v/sdc
copy 2 identical usb drives that are the same size
dd if=/de­v/sdb of=fla­sh_­dri­ve.img
make a raw image of the drive

creating CD-ROM images

dd if=/de­v/cdrom of=ubu­ntu.iso
copy the contents of a cd to an image file
cdrdao
is used for audio cds
creating an iso from a collection of files
geniso­image -o cd-rom.iso -R -J ~/cd-r­om-­files
if you had a directory called /cd-ro­m-f­iles, you could use this command to make an image of the directory
the -R -J options defined
the allow the use of long filenames
mounting an iso image directly
using the -o loop with mount
mkdir /mnt/i­so_­image
then the next line down
mount -t iso9660 -o loop image.iso /mnt/i­so_­image
mounts the iso as a virtual drive
blanking a RW CD
wodim dev=/d­ev/cdrw blank=fast
there are other types of blanking
writing an image file
wodim dev=/d­ev/cdrw image.iso
writes an image to cd

MD5 checksum

md5sum image.iso
will give you the md5 checksum value
md5sum /dev/cdrom
a cd-r write in disc at once can be checked like this
 

lynis (audit­ing­,ha­rde­ning)

sudo apt install lynis
install it
lynis audit system
perform local security scan
lynis show version
version
--verbose
details
--pentest
non privileged scan

systemctl (services)

systemctl -all or -a
see all loaded processes
list-units
list units currently in memory
list-s­ockets
list sockets currently in memory
list-u­nit­-files
list installed unit files
poweroff
turn the computer off
reboot
shutdown and restart
is-sys­tem­-ru­nning
checks to see if the system is running
--type service --state running
searching for running services

ps (running processes)

ps -e
all running processes
ps aux | grep telnet
search for telnet running
ps ####
# = number for PID to view
ps -aux
custom running process search
ps --help all
list more commands
ps
report a snapshot of the current running processes
top
display tasks with the top active ones
jobs
list active jobs
bg
place a job in the background
fg
place a job in the foreground
kill
send a signal to a process via PID
killall
kill process by name
shutdown
shut down or reboot the system
xlogo
creates a nonsense xlogo app for debuging and testing ps controls
[CTRL-c]
terminates programs started in terminal
xlogo &
& will make a program start in the background
fg %1
will bring the program to the foreground
[CTRL-z]
stops or pauses a process
bg %1
put program in background
killall [process name]
killall xlogo for example if multiples are running
pstree
outputs a process list in a tree pattern
vmstat
system resource snapshot [vmstat5] for continuous feed
xload
GUI draws a graph, showing sys stats overtime
tload
a terminal version of xload
tload
a terminal version of xload

netstat

netstat
-tulpn
-l (L)
display listening sockets
-n
don't resolve names
-p
display PID
-s
an overview - statistics
-g
group member­ships
-r
router table
-i
interface table

Custom­izing the Prompt

adjust how the prompt is displayed and operates
echo $PS1
display the current prompt setup
ps1_ol­d="$­PS1­"
make a backup before making changes called ps1_old. check with echo $ps1_old
PS1="$p­s1_­old­"
restore the original
PS1=
clear all prompt data (no visible prompt)
PROMPT VALUES
ubuntu default value is: [\u@\h \W]\$
PS1="\$ "
a minimal prompt
\a
ASCII bell. Makes the computer beep
\d
current date in day, month, date format
\h
hostname of the local machine minus the domain
\H
full hostname
\j
number of jobs in the current shell
\l
name of the current terminal device
\n
a newline character
\r
a carriage return
\s
name of the shell program
\t
current time in 24hour H:M:S
\T
current time in 12hour format
\@
current time in 12hour am/pm format
\A
current time in 24 hour H:M
\u
username of the current user
\v
version number of the shell
\V
version and release number of the shell
\w
name of the current working directory
\W
last part of the working directory
\!
history number of the current command
\#
number of commands entered in shell
\$
displays the $ character unless you have root, in that case it displays #
\[
the start of a series of one or more non-pr­inting characters
\]
the end of a non-pr­inting character sequence
COLOR TEXT
\033[0;30m
black
\033[0;31m
red
\033[0;32m
green
\033[0;33m
brown
\033[0;34m
blue
\033[0;35m
purple
\033[0;36m
cyan
\033[0;37m
light grey
\033[1;30m
dark grey
\033[1;31m
light red
\033[1;32m
light green
\033[1;33m
yellow
\033[1;34m
light blue
\033[1;35m
light purple
\033[1;36m
light cyan
\033[1;37m
white
BACK­GROUND COLOR
\033[0;40m
black
\033[0;41m
red
\033[0;42m
green
\033[0;43m
brown
\033[0;44m
blue
\033[0;45m
purple
\033[0;46m
cyan
\033[0;47m
light gray

Searching for files commands

locate
find files by name
find
search for files in directory hierarchy
xargs
build and execute command lines from standard input
touch
change file times
stat
display file or filesystem status
locate (find files the easy way)
locate bin/zip
locate will search for any string with bin and zip
locate zip | grep bin
and fancier search
find (find files the hard way)
find ~
a list of direct­ories in our home dir
find ~ | wc -l
use word count to find how many files
find ~ -type d | wc -l
find how many direct­ories with word count
find ~ -type f | wc -l
find regular files with word count
find ~ type f -name "­*.J­PG" -size +1M | wc -l
find files with the name .jpg larger than 1 mb and count them
find test
-cmin n
match files of dirs whose content was modified exactly n minutes ago
-cnewer file
match files or direct­ories whose content was last modified more recently than the file named
-ctime
match files or dirs that were modified within the last 24hours
-empty
match empty files or dirs
-group name
match files or dirs belonging to a group
-iname pattern
like name but case sensitive
-inum n
match files with inode number n
-mmin n
match files of dir whose contents were modified n mins ago
-mtime n
match files or dirs whose contents where modified n 24 hours ago
-name pattern
match files with wildcard pattern
-newer file
match files or dirs whose content was modifies more recently than specified file
-nouser
match files or dirs that do not belong to a user
-nogroup
match files that do not belong to a group
-perm mode
match files that have permission set to a specific mode
-samefile name
match files with the same inode number, similar to -inum test
-size n
match file of size n
-type c
match files of c type
-user name
match files or dir belonging to user name
find logical operat­ors
-and
match if both sides are true, also known as -a
-or
match is one side is true also known as -o
-not
match if the following test is false, also know as -!
( )
group tests together to form larger expres­sions
exam­ples
-type f -and -not -perms 0600
testing for bad permis­sions by testing for good ones
find ~ (-type f -not - perms 0600) -or (-type d -not -perms 0700)
test for bad files and direct­ories
actions for find
-delete
delete the currently matching file(see warning)
-ls
perform the equivalent of ls -dils on the matching file.
-print
output the full pathname of the file
-print0
used to correctly print file names with spaces
-quit
quit once a match has been made
warning for delete
always use -print as a substitute for -delete to see what will be deleted
find ~ -type f -name '*.BAK' -print
-print the files to output before deleting
find ~ -type f -name '*.BAK' -delete
then proceed if you wish to delete still