Cheatsheet DUMP

Bash Cheatsheet

CommandDescription
lsList directory contents
cdChange directory
pwdPrint working directory
cp source destinationCopy files or directories
mv source destinationMove/rename files or directories
rm fileRemove files
mkdir directoryCreate a new directory
rmdir directoryRemove an empty directory
echo "text"Print text to the terminal
cat fileConcatenate and display file content
less fileView file content one screen at a time
grep "pattern" fileSearch for a pattern in a file
find path -name "pattern"Find files and directories
ps auxDisplay currently running processes
kill PIDKill a process by PID
topDisplay and update sorted process list
chmod permissions fileChange file permissions
chown user:group fileChange file owner and group
df -hDisplay disk usage in human-readable format
du -sh directoryDisplay directory size in human-readable format
ln -s target link_nameCreate a symbolic link
alias name='command'Create an alias for a command
export VARIABLE=valueSet an environment variable
historyShow command history
tar -czf archive.tar.gz fileCreate a compressed archive using gzip
tar -xzf archive.tar.gzExtract a compressed archive using gzip
uptimeShow how long the system has been running
whoamiDisplay the current username
sudo commandExecute a command as the superuser
ssh user@hostConnect to a remote host via SSH
scp source user@host:destinationCopy files over SSH
crontab -eEdit cron jobs
jobsList background jobs
bg job_idResume a background job
fg job_idBring a background job to the foreground
nohup command &Run a command immune to hangups
diff file1 file2Compare the contents of two files
source fileRead and execute commands from a file in the current shell

Redirection Cheatsheet

CommandDescription
command > fileRedirect standard output (stdout) to a file (overwrite)
command >> fileRedirect standard output (stdout) to a file (append)
command 2> fileRedirect standard error (stderr) to a file (overwrite)
command 2>> fileRedirect standard error (stderr) to a file (append)
command &> fileRedirect both standard output (stdout) and standard error (stderr) to a file (overwrite)
command &>> fileRedirect both standard output (stdout) and standard error (stderr) to a file (append)
command < fileRedirect input from a file
command <<< "string"Redirect a string as input
command1 \| command2Use the output of command1 as input for command2 (pipe)
command1 \|& command2Pipe both stdout and stderr of command1 to command2 (bash 4.0+)
command > /dev/nullDiscard standard output (stdout)
command 2> /dev/nullDiscard standard error (stderr)
command &> /dev/nullDiscard both standard output (stdout) and standard error (stderr)
command > file 2>&1Redirect stdout to a file and stderr to the same file
command 2>&1 > fileRedirect stderr to the current stdout, then redirect stdout to a file
command1 2>&1 \| command2Redirect both stdout and stderr of command1 to command2
command > file1 2> file2Redirect stdout to file1 and stderr to file2
command < file1 > file2Redirect input from file1 and output to file2
exec > fileRedirect all subsequent stdout in the script to a file
exec 2> fileRedirect all subsequent stderr in the script to a file
exec > /dev/ttyRestore stdout to the terminal
exec 2> /dev/ttyRestore stderr to the terminal
command1 \| tee filePipe output of command1 to file and also display it on the terminal
command1 \| tee -a filePipe output of command1 to file (append) and also display it on the terminal
command << EOFHere document: redirect multiple lines of input to a command until EOF
command <<- EOFHere document with leading tab strip: redirect input until EOF
command <&-Close standard input (stdin)
command >&-Close standard output (stdout)
command 2>&-Close standard error (stderr)

Important System Directories and Files

/etc

Directory/FileDescription
/etc/passwdUser account information
/etc/shadowSecure user account information (passwords)
/etc/groupGroup account information
/etc/gshadowSecure group account information
/etc/fstabFilesystem mount table
/etc/hostsStatic table lookup for hostnames
/etc/resolv.confDNS server information
/etc/hostnameSystem's hostname
/etc/sysconfig/networkBasic network configuration
/etc/sysconfig/network-scripts/Network scripts and configuration files
/etc/crontabCron job schedule
/etc/cron.d/Additional cron job schedules
/etc/ssh/sshd_configSSH server configuration
/etc/sudoerssudo configuration file
/etc/systemd/system/Systemd unit files for services and targets
/etc/selinux/configSELinux configuration file
/etc/yum.confYUM package manager configuration
/etc/yum.repos.d/Repository configuration files for YUM

/var

Directory/FileDescription
/var/log/Directory containing log files
/var/log/messagesGeneral system log file
/var/log/secureSecurity and authentication log
/var/log/audit/Audit log files
/var/log/dmesgKernel ring buffer log
/var/log/httpd/Apache HTTP server logs
/var/spool/cron/User crontab files
/var/spool/mail/User mail files
/var/lib/Variable state information
/var/lib/mysql/MySQL database files
/var/lib/pgsql/PostgreSQL database files
/var/www/html/Default directory for web server content

/usr

Directory/FileDescription
/usr/bin/User binaries
/usr/sbin/System binaries
/usr/local/Local software and custom scripts
/usr/share/Shared data and resources for applications
/usr/lib/Libraries for binaries in /usr/bin and /usr/sbin
/usr/lib64/64-bit libraries
/usr/include/Header files for C programming
/usr/src/Source code files
/usr/share/doc/Documentation files for installed packages
/usr/share/man/Manual pages

/boot

Directory/FileDescription
/boot/vmlinuz-Linux kernel image
/boot/initramfs-Initial RAM filesystem
/boot/grub2/GRUB 2 bootloader configuration and files
/boot/efi/EFI boot files

/proc

Directory/FileDescription
/proc/cpuinfoCPU information
/proc/meminfoMemory information
/proc/versionKernel version
/proc/cmdlineKernel command line
/proc/devicesDevice information
/proc/diskstatsDisk statistics
/proc/uptimeSystem uptime
/proc/loadavgSystem load average
/proc/mountsMounted filesystems
/proc/partitionsPartition information
/proc/swapsSwap space utilization
/proc/sys/Kernel tunable parameters
/proc/net/Network status information

/sys

Directory/FileDescription
/sys/class/Information about device classes
/sys/block/Information about block devices
/sys/fs/Filesystem information
/sys/kernel/Kernel information and tunable parameters
/sys/module/Information about loaded kernel modules
/sys/devices/Information about devices

/dev

Directory/FileDescription
/dev/sdaFirst SCSI disk drive
/dev/sdbSecond SCSI disk drive
/dev/ttyTerminal devices
/dev/nullNull device (discard output)
/dev/randomRandom number generator
/dev/urandomNon-blocking random number generator

Vim Cheatsheet

CommandDescription
iEnter insert mode
EscExit insert mode
:wSave the file
:qQuit Vim
:wqSave and quit Vim
:q!Quit without saving
:e filenameOpen a file
:nOpen the next file
:pOpen the previous file
/patternSearch for a pattern
nRepeat the last search
NRepeat the last search in the opposite direction
:s/old/new/gReplace all occurrences of old with new in the current line
:%s/old/new/gReplace all occurrences of old with new in the file
yyYank (copy) the current line
pPaste the yanked text
ddDelete the current line
uUndo the last action
Ctrl-rRedo the last undone action
ggGo to the first line of the file
GGo to the last line of the file
0Go to the beginning of the line
$Go to the end of the line
dGDelete from the current line to the end of the file
vEnter visual mode
VEnter visual line mode
Ctrl-vEnter visual block mode
:helpOpen Vim help
:!commandExecute an external command
:r !commandRead the output of a command into the current file
:set numberShow line numbers
:set nonumberHide line numbers
:syntax onEnable syntax highlighting
:syntax offDisable syntax highlighting

tmux Cheatsheet

CommandDescription
tmux new -s session_nameCreate a new session named session_name
tmux attach -t session_nameAttach to an existing session named session_name
tmux list-sessionsList all sessions
tmux kill-session -t session_nameKill the session named session_name
tmux new-window -n window_nameCreate a new window named window_name
tmux split-window -hSplit the current window horizontally
tmux split-window -vSplit the current window vertically
tmux select-pane -t :0Select pane 0
tmux resize-pane -LResize the current pane to the left
tmux resize-pane -RResize the current pane to the right
tmux resize-pane -UResize the current pane upwards
tmux resize-pane -DResize the current pane downwards
tmux kill-pane -t pane_numberKill the pane with the specified pane_number
tmux list-windowsList all windows in the current session
tmux kill-window -t window_numberKill the window with the specified window_number
tmux rename-window new_nameRename the current window to new_name
tmux list-panesList all panes in the current window
tmux swap-pane -s pane1 -t pane2Swap the position of pane1 and pane2
tmux move-pane -t target_paneMove the current pane to target_pane
tmux set-option -g prefix C-aChange the prefix key to Ctrl-a
tmux bind-key [key] [command]Bind a key to a tmux command
tmux unbind-key [key]Unbind a key from a tmux command
tmux source-file ~/.tmux.confReload the tmux configuration file
tmux save-buffer ~/buffer.txtSave the tmux paste buffer to a file
tmux show-options -gShow all global options
tmux display-message "message"Display a message in the status line
tmux clock-modeEnter clock mode in the current pane
tmux list-keysList all key bindings
tmux capture-pane -S -100Capture the last 100 lines of the current pane
tmux show-environmentShow the tmux environment variables
tmux detach-client -t session_nameDetach the client from session_name
tmux rename-session new_session_nameRename the current session to new_session_name
tmux rotate-window -URotate the current window upwards
tmux rotate-window -DRotate the current window downwards
tmux list-clientsList all clients
tmux select-layout even-horizontalArrange panes in an even horizontal layout
tmux select-layout even-verticalArrange panes in an even vertical layout
tmux select-layout tiledArrange panes in a tiled layout

tmux Hotkeys Cheatsheet

HotkeyDescription
Ctrl-bDefault prefix key (can be changed)
Ctrl-b ?List all key bindings
Ctrl-b dDetach from the current session
Ctrl-b cCreate a new window
Ctrl-b ,Rename the current window
Ctrl-b wList all windows
Ctrl-b nMove to the next window
Ctrl-b pMove to the previous window
Ctrl-b lMove to the last (previously active) window
Ctrl-b &Kill the current window
Ctrl-b %Split the current pane vertically
Ctrl-b "Split the current pane horizontally
Ctrl-b xKill the current pane
Ctrl-b oSwitch to the next pane
Ctrl-b ;Switch to the last active pane
Ctrl-b qDisplay pane numbers
Ctrl-b zToggle pane zoom
Ctrl-b {Swap pane with the previous pane
Ctrl-b }Swap pane with the next pane
Ctrl-b SpaceToggle through layouts
Ctrl-b Ctrl-oRotate panes
Ctrl-b tShow a clock
Ctrl-b mMark the current pane
Ctrl-b 'Prompt for an index to switch to
Ctrl-b !Break the current pane into a new window
Ctrl-b sList all sessions
Ctrl-b :Enter the tmux command prompt
Ctrl-b [Enter copy mode (scrollback buffer)
Ctrl-b ]Paste the buffer
Ctrl-b -Split the window vertically
Ctrl-b =Split the window horizontally
Ctrl-b fFind window by text
Ctrl-b rReload tmux configuration

SSH Cheatsheet

CommandDescription
ssh user@hostConnect to a remote host
ssh -p port user@hostConnect to a remote host on a specific port
ssh -i keyfile user@hostConnect using a specific private key file
ssh-copy-id user@hostCopy your public key to a remote host
ssh-keygen -t rsa -b 4096Generate a new RSA key pair
ssh-add keyfileAdd a private key to the SSH agent
ssh-agent bashStart the SSH agent
scp source user@host:destinationCopy files to a remote host
scp user@host:source destinationCopy files from a remote host
rsync -avz source user@host:destinationSync files to a remote host
rsync -avz user@host:source destinationSync files from a remote host
ssh user@host commandExecute a command on a remote host
ssh -L local_port:remote_host:remote_port user@hostCreate an SSH tunnel (local forwarding)
ssh -R remote_port:local_host:local_port user@hostCreate an SSH tunnel (remote forwarding)
ssh -D local_port user@hostCreate a dynamic SOCKS proxy
~.Terminate the SSH session
~COpen command line interface during an SSH session
~&Background the SSH session
ssh -X user@hostEnable X11 forwarding
ssh -v user@hostVerbose mode (debugging)
ssh -vv user@hostMore verbose mode
ssh -q user@hostQuiet mode (suppress warnings)
ssh -f user@host commandRun SSH in the background
ssh -N user@hostDo not execute a remote command
ssh -o option=value user@hostSet an option for the SSH connection
ssh -c cipher user@hostSpecify the cipher to use
ssh-keyscan hostRetrieve SSH public keys from a host
sshfs user@host:remote_dir local_dirMount a remote directory over SSH

Git Cheatsheet

CommandDescription
git initInitialize a new Git repository
git clone repository_urlClone an existing repository
git statusShow the status of the working directory
git add fileStage changes for commit
git commit -m "message"Commit staged changes with a message
git push origin branchPush commits to the remote repository
git pull origin branchPull updates from the remote repository
git fetchFetch changes from the remote repository
git merge branchMerge a branch into the current branch
git branchList all branches
git branch branch_nameCreate a new branch
git checkout branch_nameSwitch to a different branch
git checkout -b branch_nameCreate and switch to a new branch
git logShow commit history
git log --onelineShow commit history in a condensed form
git diffShow changes between commits, commit and working tree, etc
git reset --hard commitReset the working directory and index to a specific commit
git revert commitRevert a specific commit
git stashStash changes in a dirty working directory
git stash popApply stashed changes
git remote -vShow remote repositories
git remote add name urlAdd a remote repository
git tagList tags
git tag tag_nameCreate a new tag
git rm fileRemove a file from the working directory and index
git mv old_name new_nameRename or move a file
git blame fileShow what revision and author last modified each line
git show commitShow various types of objects
git config --global user.name "name"Set the global username
git config --global user.email "email"Set the global email
git rebase branchReapply commits on top of another base tip
git cherry-pick commitApply changes from a specific commit
git bisect startStart binary search to find the commit that introduced a bug
git archive --format zip --output file.zip HEADCreate a zip archive of the current branch
git gcCleanup unnecessary files and optimize the local repository

Systemd Cheatsheet

CommandDescription
systemctl start serviceStart a service
systemctl stop serviceStop a service
systemctl restart serviceRestart a service
systemctl reload serviceReload a service's configuration
systemctl enable serviceEnable a service to start on boot
systemctl disable serviceDisable a service from starting on boot
systemctl status serviceShow the status of a service
systemctl is-active serviceCheck if a service is active
systemctl is-enabled serviceCheck if a service is enabled
systemctl list-unitsList all loaded units
systemctl list-unit-filesList installed unit files
systemctl daemon-reloadReload systemd manager configuration
journalctl -u serviceView logs for a specific service
journalctl -fFollow the system journal
systemctl mask serviceMask a service to prevent it from being started
systemctl unmask serviceUnmask a service
systemctl set-default targetSet the default target (e.g., multi-user, graphical)
systemctl get-defaultGet the current default target
systemctl isolate targetChange to a different target
systemctl show serviceShow properties of a unit
systemctl cat serviceShow the unit file of a service
systemctl edit serviceEdit a unit file (creates an override file)
systemctl reset-failed serviceReset the failed state of a unit
systemctl poweroffPower off the system
systemctl rebootReboot the system
systemctl suspendSuspend the system
systemctl hibernateHibernate the system
systemctl hybrid-sleepHibernate and suspend the system
systemd-analyze blameShow the time taken to initialize each service
systemd-analyze critical-chainShow the critical chain of units
systemd-analyze plot > plot.svgGenerate a graphical representation of the boot process
timedatectlControl the system time and date
hostnamectlControl the system hostname
localectlControl the system locale
loginctlControl the system logind

Docker Cheatsheet

CommandDescription
docker psList running containers
docker ps -aList all containers
docker imagesList all images
docker pull imagePull an image from a registry
docker run imageRun a container from an image
docker run -d imageRun a container in detached mode
docker run -it imageRun a container in interactive mode
docker stop containerStop a running container
docker start containerStart a stopped container
docker restart containerRestart a container
docker rm containerRemove a container
docker rmi imageRemove an image
docker exec -it container bashExecute a command in a running container
docker logs containerView logs of a container
docker build -t image .Build an image from a Dockerfile
docker-compose upStart containers defined in docker-compose.yml
docker-compose downStop and remove containers defined in docker-compose.yml
docker network lsList all networks
docker network create networkCreate a new network
docker volume lsList all volumes
docker volume create volumeCreate a new volume
docker inspect containerDisplay detailed information on a container
docker tag source_image target_imageTag an image
docker push imagePush an image to a registry
docker pull imagePull an image from a registry
docker save -o image.tar imageSave an image to a tar file
docker load -i image.tarLoad an image from a tar file
docker stats containerDisplay resource usage statistics of a container
docker top containerDisplay the running processes of a container
docker cp source_path container:dest_pathCopy files/folders between a container and the local filesystem
docker update --cpus=2 containerUpdate resource limits of a container
docker history imageShow the history of an image
docker diff containerInspect changes to files or directories on a container’s filesystem
docker export container -o container.tarExport a container’s filesystem to a tar archive
docker import file.tarImport a tarball to create a filesystem image

Kubernetes Cheatsheet

CommandDescription
kubectl get nodesList all nodes
kubectl get podsList all pods in the default namespace
kubectl get pods -n namespaceList all pods in a specific namespace
kubectl get servicesList all services in the default namespace
kubectl describe pod pod_nameShow detailed information about a specific pod
kubectl logs pod_namePrint the logs of a specific pod
kubectl exec -it pod_name -- bashExecute a command in a running pod
kubectl apply -f file.yamlApply a configuration file
kubectl create -f file.yamlCreate resources from a configuration file
kubectl delete -f file.yamlDelete resources defined in a configuration file
kubectl scale --replicas=3 deployment/appScale a deployment to 3 replicas
kubectl rollout status deployment/appCheck the rollout status of a deployment
kubectl rollout undo deployment/appRoll back a deployment
kubectl expose deployment app --type=LoadBalancer --port=80Expose a deployment as a service
kubectl port-forward pod_name 8080:80Forward a local port to a port on a pod
kubectl get namespacesList all namespaces
kubectl create namespace namespaceCreate a new namespace
kubectl config set-context --current --namespace=namespaceSet the current namespace
kubectl get eventsList all events
kubectl get secretsList all secrets in the default namespace
kubectl get configmapsList all configmaps in the default namespace
kubectl describe node node_nameShow detailed information about a specific node
kubectl get deploymentList all deployments in the default namespace
kubectl describe service service_nameShow detailed information about a specific service
kubectl set image deployment/app app=nginx:1.16Update the image of a deployment
kubectl edit deployment appEdit a resource on the server
kubectl delete pod pod_nameDelete a specific pod
kubectl delete service service_nameDelete a specific service
kubectl apply -f https://k8s.io/examples/application/deployment.yamlApply a deployment from a URL
kubectl get pvcList all persistent volume claims
kubectl get pvList all persistent volumes
kubectl cordon node_nameMark a node as unschedulable
kubectl drain node_nameDrain a node by evicting all pods
kubectl taint nodes node_name key=value:NoScheduleTaint a node to prevent scheduling

Ansible Cheatsheet

CommandDescription
ansible all -m pingPing all hosts
ansible-playbook playbook.yamlRun a playbook
ansible all -a "command"Run a command on all hosts
ansible all -m setupGather facts from all hosts
ansible all -m yum -a "name=package state=present"Install a package using yum
ansible all -m copy -a "src=/local/path dest=/remote/path"Copy files to remote hosts
ansible-vault create secret.yamlCreate an encrypted file
ansible-vault edit secret.yamlEdit an encrypted file
ansible-vault decrypt secret.yamlDecrypt an encrypted file
ansible-playbook --ask-vault-password playbook.yamlRun a playbook with vault password
ansible-galaxy install role_nameInstall a role from Ansible Galaxy
ansible-galaxy listList installed roles
ansible-doc -lList all modules
ansible-doc module_nameShow documentation for a specific module
ansible-playbook -i inventory playbook.yamlRun a playbook with a specific inventory
ansible all -m service -a "name=service state=started"Manage services on remote hosts
ansible all -m file -a "path=/remote/path state=directory"Ensure a directory exists on remote hosts
ansible all -m user -a "name=username state=present"Ensure a user exists on remote hosts
ansible-playbook --check playbook.yamlRun a playbook in check mode
ansible-playbook --diff playbook.yamlShow changes made by the playbook
ansible-playbook -e "variable=value" playbook.yamlPass extra variables to the playbook
ansible-playbook --tags "tag_name" playbook.yamlRun playbook tasks with specific tags
ansible-inventory --list -i inventoryList inventory hosts
ansible-inventory --graph -i inventoryShow inventory graph
ansible-config dumpDump the Ansible configuration
ansible-config listList all Ansible configuration options
ansible-pull -U repo_urlPull and run a playbook from a remote Git repository
ansible-playbook --limit "host_pattern" playbook.yamlLimit playbook run to specific hosts
ansible-playbook --start-at-task "task_name" playbook.yamlStart playbook run at a specific task
ansible-galaxy init role_nameInitialize a new role

iptables Cheatsheet

CommandDescription
iptables -LList all rules
iptables -A chain -j targetAppend a rule to a chain
iptables -I chain rule_num -j targetInsert a rule at a specific position in a chain
iptables -D chain rule_numDelete a rule from a chain by number
iptables -FFlush all rules
iptables -XDelete all user-defined chains
iptables -P chain targetSet the default policy for a chain
iptables -N chainCreate a new user-defined chain
iptables -A INPUT -p tcp --dport port -j ACCEPTAllow incoming TCP traffic on a specific port
iptables -A OUTPUT -p tcp --sport port -j ACCEPTAllow outgoing TCP traffic on a specific port
iptables -A FORWARD -i interface -j ACCEPTAllow forwarding from a specific interface
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPTAllow established and related connections
iptables -A INPUT -s ip_address -j DROPBlock traffic from a specific IP address
iptables -A INPUT -p icmp -j ACCEPTAllow ICMP (ping) traffic
iptables -A INPUT -p udp --dport port -j ACCEPTAllow incoming UDP traffic on a specific port
iptables -A INPUT -p tcp --dport 22 -j ACCEPTAllow SSH traffic
iptables -A INPUT -j REJECTReject all other incoming traffic
iptables-save > /etc/iptables/rules.v4Save the current rules to a file
iptables-restore < /etc/iptables/rules.v4Restore rules from a file

nftables Cheatsheet

CommandDescription
nft list rulesetList all rulesets
nft add table inet filterCreate a new table
nft add chain inet filter input { type filter hook input priority 0; }Create a new chain
nft add rule inet filter input ip saddr ip_address dropDrop traffic from a specific IP address
nft add rule inet filter input tcp dport port acceptAllow incoming TCP traffic on a specific port
nft add rule inet filter input udp dport port acceptAllow incoming UDP traffic on a specific port
nft add rule inet filter input icmp type echo-request acceptAllow ICMP (ping) traffic
nft add rule inet filter input ct state established,related acceptAllow established and related connections
nft add rule inet filter input iifname interface acceptAllow traffic from a specific interface
nft add rule inet filter output tcp sport port acceptAllow outgoing TCP traffic on a specific port
nft add rule inet filter forward iifname interface oifname interface acceptAllow forwarding between interfaces
nft delete rule inet filter input handle handle_numberDelete a specific rule by handle number
nft delete chain inet filter inputDelete a chain
nft delete table inet filterDelete a table
nft -f /etc/nftables.confLoad rules from a configuration file
nft save > /etc/nftables.confSave the current ruleset to a file
nft -i /etc/nftables.confLoad rules from a file interactively
nft monitorMonitor changes to the ruleset
nft add set inet filter blacklist { type ipv4_addr; }Create an IP set
nft add element inet filter blacklist { ip_address }Add an IP address to the set
nft delete element inet filter blacklist { ip_address }Remove an IP address from the set
nft add rule inet filter input ip saddr @blacklist dropDrop traffic from IP addresses in the set

Cron Cheatsheet

CommandDescription
crontab -eEdit the current user's crontab
crontab -lList the current user's crontab
crontab -rRemove the current user's crontab
crontab -u user -eEdit another user's crontab
crontab -u user -lList another user's crontab
crontab -u user -rRemove another user's crontab
@reboot commandRun once at startup
@yearly commandRun once a year (0 0 1 1 *)
@annually commandRun once a year (0 0 1 1 *)
@monthly commandRun once a month (0 0 1 * *)
@weekly commandRun once a week (0 0 * * 0)
@daily commandRun once a day (0 0 * * *)
@midnight commandRun once a day (0 0 * * *)
@hourly commandRun once an hour (0 * * * *)
* * * * * commandRun every minute
*/5 * * * * commandRun every 5 minutes
0 * * * * commandRun at the beginning of every hour
0 0 * * * commandRun at midnight every day
0 0 1 * * commandRun at midnight on the first of every month
0 0 1 1 * commandRun at midnight on January 1st
0 9 * * 1-5 commandRun at 9 AM on weekdays
0 22 * * 1-5 commandRun at 10 PM on weekdays
MAILTO="email@example.com"Send cron job output to the specified email address
0 0 * * * /path/to/script.shRun a script daily at midnight
0 5 * * * /path/to/backup.shRun a backup script daily at 5 AM
*/10 * * * * /path/to/check.shRun a script every 10 minutes
0 0 * * 0 /path/to/weekly.shRun a script weekly on Sundays at midnight
0 0 1 * * /path/to/monthly.shRun a script monthly on the first day at midnight
0 0 1 1 * /path/to/yearly.shRun a script yearly on January 1st at midnight

awk Cheatsheet

CommandDescription
awk '{print}' filePrint all lines in a file
awk '{print $1}' filePrint the first field of each line
awk '{print $1, $2}' filePrint the first and second fields of each line
awk '/pattern/ {print}' filePrint lines matching a pattern
awk 'NR==line_number' filePrint a specific line number
awk 'NR==start, NR==end' filePrint a range of lines
awk '{sum += $1} END {print sum}' fileSum the first field of all lines
awk 'BEGIN {print "Header"} {print} END {print "Footer"}' fileAdd a header and footer to the output
awk -F, '{print $1}' fileSpecify a field separator (comma in this case)
awk '{if ($1 > 10) print}' filePrint lines where the first field is greater than 10
awk '{gsub(/old/, "new"); print}' fileReplace all occurrences of "old" with "new"
awk '{print NR, $0}' filePrint line numbers with output
awk '{print length($0)}' filePrint the length of each line
awk '{print $NF}' filePrint the last field of each line
awk '{print $(NF-1)}' filePrint the second to last field of each line
awk '{count[$1]++} END {for (word in count) print word, count[word]}' fileCount occurrences of each word in the first field
awk 'NR % 2 == 0 {print}' filePrint every second line
awk '{print toupper($0)}' fileConvert text to uppercase
awk '{print tolower($0)}' fileConvert text to lowercase
awk 'BEGIN {FS=":"; OFS="-"} {print $1, $2}' fileChange input and output field separators

sed Cheatsheet

CommandDescription
sed 's/old/new/' fileReplace the first occurrence of "old" with "new"
sed 's/old/new/g' fileReplace all occurrences of "old" with "new"
sed -i 's/old/new/g' fileReplace all occurrences in the file (in-place)
sed 's/old/new/2' fileReplace the second occurrence of "old" with "new"
sed 's/old/new/gi' fileReplace all occurrences, case insensitive
sed '1,3s/old/new/' fileReplace occurrences between lines 1 and 3
sed '3s/old/new/' fileReplace occurrences on the third line
sed '/pattern/s/old/new/' fileReplace occurrences on lines matching a pattern
sed 's/^/prefix/' fileAdd a prefix to each line
sed 's/$/suffix/' fileAdd a suffix to each line
sed '/pattern/d' fileDelete lines matching a pattern
sed '3d' fileDelete the third line
sed '1,3d' fileDelete lines 1 through 3
sed '$d' fileDelete the last line
sed -n '2,4p' filePrint lines 2 through 4
sed -n '/pattern/p' filePrint lines matching a pattern
sed -e 'command1' -e 'command2' fileApply multiple commands
sed 's/.*\(pattern\).*/\1/' fileExtract and print a pattern
sed 'y/abc/ABC/' fileTranslate characters
sed -i.bak 's/old/new/g' fileReplace all occurrences and create a backup file
sed '10q' fileQuit after 10 lines
sed 's/\([0-9]\{3\}\)-\([0-9]\{2\}\)-\([0-9]\{4\}\)/\1\2\3/' fileRemove dashes from SSN format
sed 's/ *$//' fileRemove trailing whitespace
sed 's/[^[:alnum:]]//g' fileRemove all non-alphanumeric characters

grep Cheatsheet

CommandDescription
grep "pattern" fileSearch for a pattern in a file
grep -i "pattern" fileCase-insensitive search
grep -v "pattern" fileInvert match, show lines that do not match
grep -r "pattern" directoryRecursively search in a directory
grep -l "pattern" fileShow file names containing the pattern
grep -c "pattern" fileCount occurrences of the pattern
grep -n "pattern" fileShow line numbers of matches
grep -w "pattern" fileMatch whole words only
grep -A num "pattern" fileShow num lines after match
grep -B num "pattern" fileShow num lines before match
grep -C num "pattern" fileShow num lines around match
grep -e "pattern1" -e "pattern2" fileSearch for multiple patterns
grep --exclude=*.txt "pattern" *Exclude files matching a pattern
grep --include=*.txt "pattern" *Include only files matching a pattern
grep -f patternfile fileUse patterns from a file
grep -q "pattern" fileQuiet mode, return 0 if pattern is found
grep --color=auto "pattern" fileHighlight matches in color
grep -o "pattern" filePrint only matching parts of a line
grep --line-buffered "pattern" fileUse line buffering (useful for streaming)

find Cheatsheet

CommandDescription
find . -name "filename"Find files by name
find . -iname "filename"Find files by name (case-insensitive)
find . -type d -name "dirname"Find directories by name
find . -type f -name "filename"Find regular files by name
find . -size +1MFind files larger than 1MB
find . -size -1MFind files smaller than 1MB
find . -mtime -1Find files modified in the last day
find . -atime -1Find files accessed in the last day
find . -user usernameFind files owned by a specific user
find . -group groupnameFind files owned by a specific group
find . -perm 644Find files with specific permissions
find . -exec command {} \;Execute a command on each file found
find . -exec rm {} \;Delete all files found
find . -printPrint the full file names
find . -maxdepth 1 -name "filename"Find files in the current directory only
find . -mindepth 2 -name "filename"Find files not in the top-level directory
find . -type lFind symbolic links
find . -type l -xtype fFind broken symbolic links
find . -emptyFind empty files and directories
find . -newer fileFind files newer than a specific file
find . -name "*.txt" -or -name "*.md"Find files matching multiple patterns
find . -path "./dir/*" -prune -o -name "*.txt" -printExclude a directory and find files
find . -ctime +10Find files changed more than 10 days ago
find . -cmin -60Find files changed in the last 60 minutes
find / -type f 2>/dev/nullFind all files on the system, ignoring permission errors

Screen Cheatsheet

CommandDescription
screenStart a new screen session
screen -S session_nameStart a new session named session_name
screen -lsList all screen sessions
screen -r session_nameResume a detached session named session_name
screen -d -r session_nameDetach and reattach to session_name
screen -X -S session_name quitKill a session named session_name
Ctrl-a dDetach from the current session
Ctrl-a cCreate a new window
Ctrl-a "List all windows
Ctrl-a 0Switch to window 0
Ctrl-a ARename the current window
Ctrl-a nSwitch to the next window
Ctrl-a pSwitch to the previous window
Ctrl-a kKill the current window
Ctrl-a Ctrl-aSwitch between the current and previous window
Ctrl-a SSplit the screen horizontally
Ctrl-a \|Split the screen vertically
Ctrl-a tabSwitch to the next region
Ctrl-a XClose the current region
Ctrl-a QClose all regions except the current one
Ctrl-a spaceToggle between layouts
Ctrl-a :resizeResize the current region
Ctrl-a :fitFit the current region to the screen
Ctrl-a [ Enter copy mode
Ctrl-a ] Paste copied text
Ctrl-a ? Show key bindings help
Ctrl-a H Begin/end logging of the session
Ctrl-a _ Lock the terminal
Ctrl-a m Monitor the current window for activity
Ctrl-a M Monitor the current window for silence
Ctrl-a D DDetach and logout from the session

rsync Cheatsheet

CommandDescription
rsync -av source destinationArchive mode, verbose
rsync -avz source destinationArchive mode, compress during transfer
rsync -av --progress source destinationShow progress during transfer
rsync -av --delete source destinationDelete extraneous files from destination
rsync -av --exclude='pattern' source destinationExclude files matching a pattern
rsync -av --include='pattern' source destinationInclude only files matching a pattern
rsync -av -e ssh source user@host:destinationUse SSH as the transport
rsync -av --dry-run source destinationPerform a trial run with no changes made
rsync -av --partial source destinationKeep partially transferred files
rsync -av --bwlimit=KBps source destinationLimit bandwidth during transfer
rsync -av --size-only source destinationSkip files that match in size
rsync -av --checksum source destinationSkip files that match in checksum
rsync -av --times source destinationPreserve modification times
rsync -av --perms source destinationPreserve permissions
rsync -av --owner source destinationPreserve owner
rsync -av --group source destinationPreserve group
rsync -av --links source destinationCopy symlinks as symlinks
rsync -av --hard-links source destinationPreserve hard links
rsync -av --copy-links source destinationCopy symlinks as files
rsync -av --copy-dirlinks source destinationTransform symlinks to directories into real dirs
rsync -av --no-links source destinationSkip copying symlinks
rsync -av --safe-links source destinationIgnore symlinks that point outside source tree
rsync -av --delete-excluded source destinationDelete excluded files from destination
rsync -av --max-size=SIZE source destinationLimit maximum size of files to transfer
rsync -av --min-size=SIZE source destinationLimit minimum size of files to transfer
rsync -av --backup source destinationBackup files that are replaced
rsync -av --backup-dir=DIR source destinationBackup files into a specific directory
rsync -av --suffix=SUFFIX source destinationDefine suffix for backup files
rsync -av --inplace source destinationUpdate destination files in place
rsync -av --append source destinationAppend data onto shorter files
rsync -av --append-verify source destinationAppend and verify full file content
rsync -av --ignore-existing source destinationSkip updating files that already exist
rsync -av --remove-source-files source destinationRemove source files after transfer

tar Cheatsheet

CommandDescription
tar -cvf archive.tar file_or_directoryCreate a tar archive
tar -xvf archive.tarExtract a tar archive
tar -tvf archive.tarList contents of a tar archive
tar -cvzf archive.tar.gz file_or_directoryCreate a gzip-compressed tar archive
tar -xvzf archive.tar.gzExtract a gzip-compressed tar archive
tar -cvjf archive.tar.bz2 file_or_directoryCreate a bzip2-compressed tar archive
tar -xvjf archive.tar.bz2Extract a bzip2-compressed tar archive
tar -cvJf archive.tar.xz file_or_directoryCreate a xz-compressed tar archive
tar -xvJf archive.tar.xzExtract a xz-compressed tar archive
tar -cvf - file_or_directory \| ssh user@host "tar -xvf - -C /destination"Copy files over SSH
tar -rf archive.tar fileAppend files to an existing tar archive
tar -uf archive.tar fileUpdate files in an existing tar archive
tar -cvf archive.tar --exclude="*.txt" file_or_directoryCreate tar archive excluding certain files
tar -cvf archive.tar --exclude-vcs file_or_directoryCreate tar archive excluding version control files
tar --delete -f archive.tar fileDelete files from a tar archive
tar -cvf archive.tar -T filelist.txtCreate tar archive from a list of files
tar -xvf archive.tar -C /destinationExtract tar archive to a specific directory
tar --strip-components=number -xvf archive.tarExtract tar archive, removing a number of leading components
tar --transform='s/old/new/' -cvf archive.tar file_or_directoryCreate tar archive with transformed file names
tar -xzvf archive.tar.gz --wildcards '*.txt'Extract specific files from a compressed tar archive

gzip Cheatsheet

CommandDescription
gzip fileCompress a file
gzip -d file.gzDecompress a file
gzip -k fileCompress a file, keeping the original
gzip -r directoryRecursively compress files in a directory
gzip -l file.gzList compressed file details
gzip -t file.gzTest compressed file integrity
gzip -v fileCompress a file with verbose output
gzip -1 fileCompress a file with fastest speed
gzip -9 fileCompress a file with best compression
zcat file.gzView contents of a compressed file
zgrep "pattern" file.gzSearch for a pattern in a compressed file
zless file.gzView a compressed file with less
zcmp file1.gz file2.gzCompare compressed files
zdiff file1.gz file2.gzShow differences between compressed files

bzip2 Cheatsheet

CommandDescription
bzip2 fileCompress a file
bzip2 -d file.bz2Decompress a file
bzip2 -k fileCompress a file, keeping the original
bzip2 -z fileCompress a file
bzip2 -t file.bz2Test compressed file integrity
bzip2 -c file > file.bz2Compress a file to standard output
bzip2 -f fileForce compression or decompression
bzip2 -v fileCompress a file with verbose output
bzip2 -1 fileCompress a file with fastest speed
bzip2 -9 fileCompress a file with best compression
bzcat file.bz2View contents of a compressed file
bzgrep "pattern" file.bz2Search for a pattern in a compressed file
bzless file.bz2View a compressed file with less
bzcmp file1.bz2 file2.bz2Compare compressed files
bzdiff file1.bz2 file2.bz2Show differences between compressed files

curl Cheatsheet

CommandDescription
curl urlFetch the content of a URL
curl -o file urlSave the content to a file
curl -O urlSave the content to a file with the same name
curl -L urlFollow redirects
curl -I urlFetch headers only
curl -d "data" urlSend data with a POST request
curl -X POST urlSend a POST request
curl -X PUT urlSend a PUT request
curl -X DELETE urlSend a DELETE request
curl -H "Header: value" urlSend a custom header
curl -u user:password urlSend basic authentication
curl -F "name=value" urlSend a multipart form data
curl -k urlAllow insecure SSL connections
curl --cert certfile urlSend a client certificate
curl -b "name=value" urlSend cookies
curl -c cookiefile urlSave cookies to a file
curl --limit-rate 100k urlLimit the transfer rate
curl --compressed urlRequest a compressed response
curl --retry num urlRetry a request on failure
curl --silent urlSilent mode (suppress output)
curl --progress-bar urlDisplay a progress bar
curl --http2 urlUse HTTP/2 protocol
curl --interface interface urlUse a specific network interface
curl --ipv4 urlUse IPv4 only
curl --ipv6 urlUse IPv6 only
curl --location-trusted urlFollow redirects and send authentication to other hosts
curl --data-urlencode "name=value" urlURL encode data
curl --max-time seconds urlSet a maximum time for the request
curl --connect-timeout seconds urlSet a maximum time for the connection
curl --proxy proxy_url urlUse a proxy server

wget Cheatsheet

CommandDescription
wget urlDownload a file
wget -O file urlSave the download with a specific name
wget -P /path urlSave the download to a specific directory
wget -c urlContinue a partially downloaded file
wget -b urlDownload in the background
wget -i fileDownload URLs listed in a file
wget -r urlDownload recursively
wget -l depth urlSet the download depth
wget -k urlConvert links to be suitable for local viewing
wget -m urlMirror a website
wget -p urlDownload all necessary files to display a webpage
wget --limit-rate=100k urlLimit the download speed
wget --user=user --password=password urlDownload with basic authentication
wget --header="Header: value" urlSend a custom header
wget --no-check-certificate urlIgnore SSL certificate errors
wget --quiet urlQuiet mode (no output)
wget --show-progress urlShow a progress bar
wget --spider urlCheck if a URL exists
wget --no-clobber urlDo not overwrite existing files
wget --timestamping urlDownload only if the remote file is newer than the local file
wget --directory-prefix=prefix urlSave files to a specific directory
wget --tries=num urlSet the number of retries
wget --wait=seconds urlWait between downloads
wget --random-wait urlWait a random amount of time between downloads
wget --delete-after urlDelete files after downloading
wget --mirror urlMirror a website
wget --recursive urlDownload files recursively
wget --level=depth urlSet the recursion depth
wget --user-agent="User-Agent" urlSet the user agent

MySQL/MariaDB Cheatsheet

CommandDescription
mysql -u user -pConnect to the MySQL server
CREATE DATABASE dbname;Create a new database
DROP DATABASE dbname;Delete a database
USE dbname;Select a database
SHOW DATABASES;List all databases
SHOW TABLES;List all tables in the selected database
DESCRIBE tablename;Show table structure
CREATE TABLE tablename (columns);Create a new table
DROP TABLE tablename;Delete a table
INSERT INTO tablename (columns) VALUES (values);Insert data into a table
SELECT * FROM tablename;Retrieve all data from a table
UPDATE tablename SET column=value WHERE condition;Update data in a table
DELETE FROM tablename WHERE condition;Delete data from a table
GRANT ALL PRIVILEGES ON dbname.* TO 'user'@'host' IDENTIFIED BY 'password';Grant privileges to a user
FLUSH PRIVILEGES;Reload privileges
SHOW GRANTS FOR 'user'@'host';Show granted privileges
REVOKE ALL PRIVILEGES ON dbname.* FROM 'user'@'host';Revoke privileges from a user
CREATE USER 'user'@'host' IDENTIFIED BY 'password';Create a new user
DROP USER 'user'@'host';Delete a user
SHOW PROCESSLIST;Show running processes
EXIT;Exit the MySQL shell
mysqldump -u user -p dbname > backup.sqlBackup a database
mysql -u user -p dbname < backup.sqlRestore a database
SHOW STATUS;Show server status
SHOW VARIABLES;Show server variables
SHOW INDEX FROM tablename;Show indexes in a table
SHOW CREATE TABLE tablename;Show the CREATE TABLE statement for a table
ALTER TABLE tablename ADD columnname datatype;Add a column to a table
ALTER TABLE tablename DROP columnname;Drop a column from a table
ALTER TABLE tablename MODIFY columnname datatype;Modify a column in a table
ALTER TABLE tablename RENAME TO newtablename;Rename a table
CREATE INDEX indexname ON tablename (columns);Create an index on a table
DROP INDEX indexname ON tablename;Drop an index from a table
SET GLOBAL max_connections = value;Set a global variable
SHOW ENGINE INNODB STATUS;Show InnoDB status

PostgreSQL Cheatsheet

CommandDescription
psql -U user -d dbnameConnect to the PostgreSQL server
CREATE DATABASE dbname;Create a new database
DROP DATABASE dbname;Delete a database
\c dbnameConnect to a database
\lList all databases
\dtList all tables in the connected database
\d tablenameShow table structure
CREATE TABLE tablename (columns);Create a new table
DROP TABLE tablename;Delete a table
INSERT INTO tablename (columns) VALUES (values);Insert data into a table
SELECT * FROM tablename;Retrieve all data from a table
UPDATE tablename SET column=value WHERE condition;Update data in a table
DELETE FROM tablename WHERE condition;Delete data from a table
GRANT ALL PRIVILEGES ON DATABASE dbname TO user;Grant privileges to a user
REVOKE ALL PRIVILEGES ON DATABASE dbname FROM user;Revoke privileges from a user
CREATE USER username WITH PASSWORD 'password';Create a new user
DROP USER username;Delete a user
\qExit the PostgreSQL shell
pg_dump -U user -d dbname -f backup.sqlBackup a database
psql -U user -d dbname -f backup.sqlRestore a database
\conninfoShow connection information
\duList all roles
\diList all indexes
\dfList all functions
\dnList all schemas
\dpList table, view, and sequence access privileges
ALTER TABLE tablename ADD columnname datatype;Add a column to a table
ALTER TABLE tablename DROP columnname;Drop a column from a table
ALTER TABLE tablename ALTER COLUMN columnname TYPE datatype;Modify a column in a table
ALTER TABLE tablename RENAME TO newtablename;Rename a table
CREATE INDEX indexname ON tablename (columns);Create an index on a table
DROP INDEX indexname;Drop an index
VACUUMClean up and optimize the database
VACUUM FULLClean up and optimize the database (full)
ANALYZECollect statistics about the database
EXPLAIN SELECT * FROM tablename;Show the execution plan for a query
SET search_path TO schema;Set the search path to a specific schema

Nginx Cheatsheet

CommandDescription
sudo systemctl start nginxStart Nginx
sudo systemctl stop nginxStop Nginx
sudo systemctl restart nginxRestart Nginx
sudo systemctl reload nginxReload Nginx configuration
sudo systemctl enable nginxEnable Nginx to start on boot
sudo systemctl disable nginxDisable Nginx from starting on boot
nginx -tTest Nginx configuration
nginx -s reloadReload Nginx configuration
nginx -s reopenReopen log files
nginx -s stopStop Nginx
nginx -s quitGracefully stop Nginx
/etc/nginx/nginx.confMain Nginx configuration file
/etc/nginx/sites-available/Directory for available site configurations
/etc/nginx/sites-enabled/Directory for enabled site configurations
sudo ln -s /etc/nginx/sites-available/site /etc/nginx/sites-enabled/Enable a site configuration
sudo unlink /etc/nginx/sites-enabled/siteDisable a site configuration
server { ... }Define a virtual server block
location / { ... }Define a location block
listen 80;Listen on port 80
listen 443 ssl;Listen on port 443 with SSL
server_name domain.com;Define the server name
root /var/www/html;Define the document root
index index.html;Define the default index file
error_page 404 /404.html;Define a custom error page
access_log /var/log/nginx/access.log;Define the access log file
error_log /var/log/nginx/error.log;Define the error log file
proxy_pass http://backend;Proxy requests to a backend server
rewrite ^/old/(.*)$ /new/$1 permanent;Rewrite URL
location ~ \.php$ { ... }Define a location block for PHP files
include /etc/nginx/conf.d/*.conf;Include additional configuration files
ssl_certificate /etc/nginx/ssl/nginx.crt;Define the SSL certificate
ssl_certificate_key /etc/nginx/ssl/nginx.key;Define the SSL certificate key
ssl_protocols TLSv1.2 TLSv1.3;Define the supported SSL protocols
ssl_ciphers HIGH:!aNULL:!MD5;Define the supported SSL ciphers

Apache Cheatsheet

CommandDescription
sudo systemctl start apache2Start Apache
sudo systemctl stop apache2Stop Apache
sudo systemctl restart apache2Restart Apache
sudo systemctl reload apache2Reload Apache configuration
sudo systemctl enable apache2Enable Apache to start on boot
sudo systemctl disable apache2Disable Apache from starting on boot
apachectl configtestTest Apache configuration
apachectl gracefulGracefully restart Apache
/etc/apache2/apache2.confMain Apache configuration file
/etc/apache2/sites-available/Directory for available site configurations
/etc/apache2/sites-enabled/Directory for enabled site configurations
sudo a2ensite siteEnable a site configuration
sudo a2dissite siteDisable a site configuration
sudo a2enmod moduleEnable a module
sudo a2dismod moduleDisable a module
sudo a2enconf configEnable a configuration
sudo a2disconf configDisable a configuration
<VirtualHost *:80> ... </VirtualHost>Define a virtual host for HTTP
<VirtualHost *:443> ... </VirtualHost>Define a virtual host for HTTPS
ServerName domain.comDefine the server name
DocumentRoot /var/www/htmlDefine the document root
DirectoryIndex index.htmlDefine the default index file
ErrorLog /var/log/apache2/error.logDefine the error log file
CustomLog /var/log/apache2/access.log combinedDefine the access log file
SSLEngine onEnable SSL
SSLCertificateFile /etc/apache2/ssl/apache.crtDefine the SSL certificate
SSLCertificateKeyFile /etc/apache2/ssl/apache.keyDefine the SSL certificate key
SSLProtocol all -SSLv2 -SSLv3Define the supported SSL protocols
SSLCipherSuite HIGH:!aNULL:!MD5Define the supported SSL ciphers
ProxyPass /app http://backend/appProxy requests to a backend server
ProxyPassReverse /app http://backend/appAdjust the URL in the Location header
RewriteEngine onEnable URL rewriting
RewriteRule ^/old/(.*)$ /new/$1 [R=301,L]Rewrite URL
<Directory /var/www/html> ... </Directory>Define directory-specific settings
Options Indexes FollowSymLinksSet directory options
AllowOverride AllAllow .htaccess to override settings
Require all grantedAllow access to a directory
Redirect permanent /old /newRedirect a URL

Firewalld Cheatsheet

CommandDescription
firewall-cmd --stateCheck the state of firewalld
firewall-cmd --reloadReload firewalld configuration
firewall-cmd --get-active-zonesList all active zones
firewall-cmd --get-default-zoneGet the default zone
firewall-cmd --zone=zone --list-allList all settings in a zone
firewall-cmd --zone=zone --add-source=sourceAdd a source to a zone
firewall-cmd --zone=zone --add-port=port/protocolAdd a port to a zone
firewall-cmd --zone=zone --remove-port=port/protocolRemove a port from a zone
firewall-cmd --zone=zone --add-service=serviceAdd a service to a zone
firewall-cmd --zone=zone --remove-service=serviceRemove a service from a zone
firewall-cmd --permanentApply changes permanently
firewall-cmd --runtime-to-permanentSave runtime changes to permanent configuration
firewall-cmd --add-masqueradeEnable masquerading (NAT)
firewall-cmd --remove-masqueradeDisable masquerading (NAT)
firewall-cmd --zone=zone --add-rich-rule='rule'Add a rich rule to a zone
firewall-cmd --zone=zone --remove-rich-rule='rule'Remove a rich rule from a zone

UFW Cheatsheet

CommandDescription
sudo ufw enableEnable UFW
sudo ufw disableDisable UFW
sudo ufw statusShow the current status of UFW and list rules
sudo ufw status verboseShow the current status of UFW with detailed information
sudo ufw allow portAllow incoming traffic on a specific port
sudo ufw allow from IPAllow incoming traffic from a specific IP address
sudo ufw allow from IP to any port portAllow incoming traffic from a specific IP to a specific port
sudo ufw allow proto tcp from IP to any port portAllow incoming TCP traffic from a specific IP to a specific port
sudo ufw deny portDeny incoming traffic on a specific port
sudo ufw deny from IPDeny incoming traffic from a specific IP address
sudo ufw deny from IP to any port portDeny incoming traffic from a specific IP to a specific port
sudo ufw delete allow portDelete an allow rule for a specific port
sudo ufw delete deny portDelete a deny rule for a specific port
sudo ufw default allow outgoingSet the default policy to allow outgoing traffic
sudo ufw default deny outgoingSet the default policy to deny outgoing traffic
sudo ufw default allow incomingSet the default policy to allow incoming traffic
sudo ufw default deny incomingSet the default policy to deny incoming traffic
sudo ufw resetReset UFW rules to the default state
sudo ufw show rawShow the raw iptables rules generated by UFW
sudo ufw logging onEnable logging for UFW
sudo ufw logging offDisable logging for UFW
sudo ufw logging lowSet logging level to low
sudo ufw logging mediumSet logging level to medium
sudo ufw logging highSet logging level to high
sudo ufw app listList all available application profiles
sudo ufw app info ApplicationShow information about a specific application profile
sudo ufw allow ApplicationAllow an application by profile
sudo ufw deny ApplicationDeny an application by profile
sudo ufw reloadReload UFW to apply changes
sudo ufw route allow proto tcp from any to any port portAllow routing for a specific port over TCP
sudo ufw route deny proto udp from any to any port portDeny routing for a specific port over UDP

SELinux Cheatsheet

CommandDescription
sestatusCheck the status of SELinux
getenforceGet the current mode of SELinux
setenforce 0Set SELinux to permissive mode
setenforce 1Set SELinux to enforcing mode
semanage boolean -lList all SELinux booleans
semanage boolean -m --on boolean_nameEnable an SELinux boolean
semanage boolean -m --off boolean_nameDisable an SELinux boolean
semanage fcontext -lList all file context mappings
semanage fcontext -a -t type '/path(/.*)?'Add a file context mapping
restorecon -Rv /pathApply file context to files
chcon -t type /pathChange the file context
ls -ZList files with SELinux context
ps -ZList processes with SELinux context
grep AVC /var/log/audit/audit.logSearch for SELinux denials in the audit log
ausearch -m avc -ts recentSearch for recent SELinux denials
audit2allow -w -aDisplay audit log entries that require policy changes
audit2allow -a -M mymoduleGenerate a policy module to allow denials
semodule -i mymodule.ppInstall a policy module
semanage port -lList all SELinux port mappings
semanage port -a -t type -p tcp portAdd a port mapping
semanage port -d -p tcp portDelete a port mapping
semanage permissive -a typeSet a domain to permissive mode
semanage permissive -d typeRemove a domain from permissive mode
seinfoDisplay SELinux policy information
semodule -lList all installed policy modules
semodule -r module_nameRemove an installed policy module
sealert -a /var/log/audit/audit.logAnalyze audit log for SELinux denials

AppArmor Cheatsheet

CommandDescription
aa-statusCheck the status of AppArmor
aa-enforce /etc/apparmor.d/profileSet a profile to enforce mode
aa-complain /etc/apparmor.d/profileSet a profile to complain mode
aa-logprofUpdate profiles based on log events
aa-genprof /path/to/executableGenerate a new profile for an executable
aa-disable /etc/apparmor.d/profileDisable a profile
aa-parse -r /etc/apparmor.d/profileReload a profile
apparmor_parser -r /etc/apparmor.d/profileReload a profile
apparmor_parser -R /etc/apparmor.d/profileRemove a profile from the kernel
aa-unconfinedList unconfined processes
aa-notifyDisplay AppArmor notifications
aa-exec -p profile -- commandExecute a command under a specific profile
aa-audit /etc/apparmor.d/profileSet a profile to audit mode
cat /var/log/syslog \| grep apparmorSearch for AppArmor messages in the syslog
grep "audit" /var/log/kern.logSearch for AppArmor audit messages in the kernel log
ls -lZ /pathList files with AppArmor context
aa-cleanprofRemove unnecessary rules from a profile
aa-enforce /etc/apparmor.d/*Set all profiles to enforce mode
aa-complain /etc/apparmor.d/*Set all profiles to complain mode
journalctl -xe \| grep apparmorSearch for AppArmor events in the journal log
sudo apparmor_parser -r /etc/apparmor.d/usr.bin.programReload a specific AppArmor profile
sudo aa-genprof /path/to/programGenerate a new profile for a program
sudo aa-logprof /var/log/syslogUpdate profiles based on log events
sudo aa-enforce /etc/apparmor.d/usr.bin.programEnforce a specific AppArmor profile
sudo aa-complain /etc/apparmor.d/usr.bin.programSet a specific AppArmor profile to complain mode

LDAP Cheatsheet

CommandDescription
ldapsearch -x -b "base_dn" "(filter)"Search for entries in the LDAP directory
ldapadd -x -D "bind_dn" -W -f file.ldifAdd entries to the LDAP directory
ldapdelete -x -D "bind_dn" -W "dn"Delete entries from the LDAP directory
ldapmodify -x -D "bind_dn" -W -f file.ldifModify entries in the LDAP directory
ldapcompare -x -D "bind_dn" -W "dn" attribute:valueCompare attribute values
ldapwhoami -x -D "bind_dn" -WShow the distinguished name of the authenticated user
ldapmodrdn -x -D "bind_dn" -W "dn" "new_rdn"Modify the RDN of an entry
slapcat -v -l backup.ldifExport the LDAP directory to an LDIF file
slapadd -v -l backup.ldifImport an LDIF file into the LDAP directory
slapindexRebuild the LDAP directory indexes
slapd -d 1Start the LDAP server in debug mode
ldapsearch -LLL -x -b "base_dn" "(filter)" attributeSearch and display specific attributes
ldapsearch -H ldap://ldap.example.com -x -b "base_dn" "(filter)"Search using a specific LDAP URI
ldapsearch -ZZ -x -b "base_dn" "(filter)"Search with StartTLS
ldapadd -ZZ -x -D "bind_dn" -W -f file.ldifAdd entries with StartTLS
ldapmodify -ZZ -x -D "bind_dn" -W -f file.ldifModify entries with StartTLS
ldapdelete -ZZ -x -D "bind_dn" -W "dn"Delete entries with StartTLS
ldapwhoami -ZZ -x -D "bind_dn" -WShow the distinguished name with StartTLS
ldapcompare -ZZ -x -D "bind_dn" -W "dn" attribute:valueCompare attribute values with StartTLS
ldapmodrdn -ZZ -x -D "bind_dn" -W "dn" "new_rdn"Modify the RDN with StartTLS
ldapsearch -Y EXTERNAL -H ldapi:/// -b "cn=config"Search the configuration directory
ldapadd -Y EXTERNAL -H ldapi:/// -f config.ldifAdd configuration entries
ldapmodify -Y EXTERNAL -H ldapi:/// -f config.ldifModify configuration entries
ldapdelete -Y EXTERNAL -H ldapi:/// "dn"Delete configuration entries

LVM Cheatsheet

CommandDescription
pvcreate /dev/sdXCreate a physical volume
pvdisplayDisplay information about physical volumes
pvscanScan all disks for physical volumes
vgcreate vgname /dev/sdXCreate a volume group
vgdisplayDisplay information about volume groups
vgscanScan all disks for volume groups
vgextend vgname /dev/sdXAdd a physical volume to a volume group
vgreduce vgname /dev/sdXRemove a physical volume from a volume group
lvcreate -L size -n lvname vgnameCreate a logical volume
lvcreate -l 100%FREE -n lvname vgnameCreate a logical volume using all free space
lvdisplayDisplay information about logical volumes
lvextend -L+size /dev/vgname/lvnameExtend a logical volume by size
lvextend -l +100%FREE /dev/vgname/lvnameExtend a logical volume using all free space
lvreduce -L-size /dev/vgname/lvnameReduce the size of a logical volume
lvremove /dev/vgname/lvnameRemove a logical volume
lvresize -L size /dev/vgname/lvnameResize a logical volume
lvrename /dev/vgname/oldname newnameRename a logical volume
vgremove vgnameRemove a volume group
pvremove /dev/sdXRemove a physical volume
vgchange -a y vgnameActivate a volume group
vgchange -a n vgnameDeactivate a volume group
vgmerge vgname1 vgname2Merge two volume groups
vgsplit vgname new_vgname /dev/sdXSplit a volume group into two
pvmove /dev/sdXMove physical extents from one physical volume to another
vgcfgbackupBackup volume group metadata
vgcfgrestore vgnameRestore volume group metadata
lvconvert --type raid1 --mirrors 1 /dev/vgname/lvnameConvert a logical volume to RAID1
lvchange -a y /dev/vgname/lvnameActivate a logical volume
lvchange -a n /dev/vgname/lvnameDeactivate a logical volume
lvscanScan for all logical volumes
vgextend vgname /dev/sdXAdd a physical volume to a volume group

ZFS Cheatsheet

CommandDescription
zpool create pool /dev/sdXCreate a new storage pool
zpool destroy poolDestroy a storage pool
zpool statusShow the status of all pools
zpool listList all pools
zpool add pool /dev/sdXAdd a device to a pool
zpool remove pool /dev/sdXRemove a device from a pool
zpool replace pool /dev/sdX /dev/sdYReplace a device in a pool
zpool scrub poolScrub the data in a pool
zpool export poolExport a pool
zpool import poolImport a pool
zfs create pool/datasetCreate a new dataset
zfs destroy pool/datasetDestroy a dataset
zfs listList all datasets
zfs mount pool/datasetMount a dataset
zfs unmount pool/datasetUnmount a dataset
zfs snapshot pool/dataset@snapshotCreate a snapshot of a dataset
zfs rollback pool/dataset@snapshotRoll back to a snapshot
zfs send pool/dataset@snapshotSend a snapshot
zfs receive pool/datasetReceive a snapshot
zfs get property pool/datasetGet a property value
zfs set property=value pool/datasetSet a property value
zfs rename pool/dataset new_nameRename a dataset
zfs clone pool/dataset@snapshot new_datasetClone a snapshot
zfs promote pool/datasetPromote a clone to a full dataset
zfs diff pool/dataset@snapshot1 pool/dataset@snapshot2Show differences between snapshots
zfs upgrade -aUpgrade all ZFS filesystems
zpool upgrade -aUpgrade all ZFS pools
zpool history poolShow command history for a pool
zpool iostat poolShow I/O statistics for a pool
zpool clear poolClear errors in a pool
zpool trim poolTrim free space in a pool
zfs hold tag pool/dataset@snapshotHold a snapshot
zfs release tag pool/dataset@snapshotRelease a held snapshot
zfs inherit property pool/datasetInherit a property from the parent

Btrfs Cheatsheet

CommandDescription
mkfs.btrfs /dev/sdXCreate a Btrfs filesystem
btrfs filesystem showShow Btrfs filesystems
btrfs filesystem df /mountpointShow disk usage of a Btrfs filesystem
btrfs filesystem balance /mountpointBalance a Btrfs filesystem
btrfs filesystem resize size /mountpointResize a Btrfs filesystem
btrfs device add /dev/sdX /mountpointAdd a device to a Btrfs filesystem
btrfs device delete /dev/sdX /mountpointRemove a device from a Btrfs filesystem
btrfs scrub start /mountpointScrub a Btrfs filesystem
btrfs scrub status /mountpointShow scrub status
btrfs balance start /mountpointStart a balance operation
btrfs balance status /mountpointShow balance status
btrfs subvolume create /mountpoint/subvolumeCreate a subvolume
btrfs subvolume delete /mountpoint/subvolumeDelete a subvolume
btrfs subvolume list /mountpointList all subvolumes
btrfs subvolume snapshot /mountpoint/subvolume /mountpoint/snapshotCreate a snapshot
btrfs send /mountpoint/subvolumebtrfs receive /mountpoint/snapshot`
btrfs subvolume set-default subvolid /mountpointSet the default subvolume
btrfs property set /mountpoint/subvolume ro trueSet a subvolume to read-only
btrfs property list /mountpoint/subvolumeList properties of a subvolume
btrfs quota enable /mountpointEnable quotas on a Btrfs filesystem
btrfs qgroup show /mountpointShow quota groups
btrfs qgroup limit size /mountpointSet a quota limit
btrfs rescue zero-log /dev/sdXRepair a corrupted log
btrfs rescue chunk-recover /dev/sdXRecover corrupted chunks
btrfs check /dev/sdXCheck a Btrfs filesystem
btrfs device scanScan for Btrfs devices
btrfs device stats /mountpointShow device statistics
btrfs filesystem defragment /mountpointDefragment a Btrfs filesystem
btrfs quota rescan -w /mountpointRescan quotas
btrfs filesystem sync /mountpointSync a Btrfs filesystem
btrfs replace start /dev/sdX /dev/sdY /mountpointReplace a device in a Btrfs filesystem
btrfs replace status /mountpointShow replace status

Network Troubleshooting Cheatsheet

CommandDescription
ping hostCheck connectivity to a host
ping -c count hostSend a specific number of ping requests
ping -i interval hostSet the interval between ping requests
ping -t ttl hostSet the time-to-live for ping packets
traceroute hostTrace the route to a host
traceroute -m max_ttl hostSet the maximum TTL
traceroute -p port hostSet the destination port
traceroute -I hostUse ICMP echo instead of UDP
traceroute -T hostUse TCP SYN instead of UDP
mtr hostNetwork diagnostic tool combining ping and traceroute
mtr -r hostRun MTR in report mode
mtr -c count hostSet the number of pings in MTR
netstat -tulnList all listening ports and services
netstat -iShow network interfaces
netstat -rnShow the routing table
netstat -sDisplay network statistics
netstat -plntShow listening TCP ports
ss -tulnList all listening ports and services (ss command)
ss -iShow network interfaces (ss command)
ss -rnShow the routing table (ss command)
ss -sDisplay network statistics (ss command)
ss -plntShow listening TCP ports (ss command)
ip addr showDisplay all IP addresses
ip link showShow network interfaces
ip route showDisplay the routing table
ip link set dev iface upBring an interface up
ip link set dev iface downBring an interface down
ifconfigDisplay network interfaces
ifconfig iface upBring an interface up
ifconfig iface downBring an interface down
ifconfig iface inet addrAssign an IP address to an interface
ifconfig iface hw ether MACAssign a MAC address to an interface
ethtool ifaceDisplay Ethernet device settings
ethtool -s iface speed 1000 duplex full autoneg onSet Ethernet device speed and duplex
tcpdump -i ifaceCapture packets on an interface
tcpdump -n host hostCapture packets to/from a specific host
tcpdump -nn port portCapture packets on a specific port
tcpdump -w file.pcapWrite packets to a file
tcpdump -r file.pcapRead packets from a file
dig domainDNS lookup for a domain
dig +short domainShort DNS lookup for a domain
dig -x ipReverse DNS lookup
nslookup domainDNS lookup for a domain (nslookup)
nslookupEnter interactive mode (nslookup)
nslookup domain serverDNS lookup using a specific DNS server

System Diagnostics and Logging Cheatsheet

dmesg

CommandDescription
dmesgDisplay all messages from the kernel ring buffer
`dmesgless`
`dmesggrep pattern`
dmesg -cClear the ring buffer after printing
dmesg -TDisplay human-readable timestamps for each message
dmesg -HEnable colorized and human-readable output
dmesg -l levelFilter messages by log level (e.g., emerg, alert, crit, err, warn, notice, info, debug)
dmesg -n levelSet the log level of messages to print
dmesg -f facilityFilter messages by facility (e.g., kern, user, mail, daemon, auth, syslog, lpr, news, uucp, cron, authpriv, ftp, local0-local7)
dmesg -rRaw output, no human-readable timestamps
dmesg --clearClear the kernel ring buffer
dmesg --level levelSet the log level for printing messages
dmesg --facility facilitySet the facility for printing messages
dmesg -wKeep waiting for new messages and print them as they come
dmesg --followAlias for -w, keep waiting for new messages

journalctl

CommandDescription
journalctlView the systemd journal
journalctl -bShow messages from the current boot
journalctl -kShow only kernel messages
journalctl -u serviceShow messages for a specific service
journalctl -fFollow new messages as they appear (similar to tail -f)
journalctl -rShow messages in reverse chronological order
journalctl --since "time"Show messages since a specific time
journalctl --until "time"Show messages until a specific time
journalctl -p levelShow messages of a specific priority level (e.g., emerg, alert, crit, err, warn, notice, info, debug)
journalctl -xeShow the last few log entries with details about system errors
journalctl --disk-usageShow the disk space used by the journal
journalctl --vacuum-time=timeRemove journal files older than the specified time
journalctl --vacuum-size=sizeRemove old journal files until the total size is below the specified size
journalctl -o json-prettyOutput logs in pretty JSON format

rsyslog (or syslog in general)

Command/ConfigurationDescription
/etc/rsyslog.confMain configuration file for rsyslog
/etc/rsyslog.d/Directory for additional configuration files
sudo systemctl restart rsyslogRestart the rsyslog service
logger "message"Add a message to the system log
/var/log/messagesGeneral system log
/var/log/secureAuthentication and security related messages
/var/log/maillogMail server logs
/var/log/cronCron job logs
/var/log/boot.logSystem boot log
/var/log/dmesgKernel ring buffer log

top / htop

CommandDescription
topDisplay real-time system information including tasks and load
htopInteractive process viewer (requires installation)
top -u usernameShow only processes for a specific user
top -p PIDShow only the specified PID(s)
htop -u usernameShow only processes for a specific user (in htop)

free

CommandDescription
freeDisplay memory usage
free -hDisplay memory usage in human-readable format
free -mDisplay memory usage in megabytes
free -gDisplay memory usage in gigabytes

vmstat

CommandDescription
vmstatDisplay virtual memory statistics
vmstat 1Display virtual memory statistics every second
vmstat -sDisplay memory statistics
vmstat -dDisplay disk statistics
vmstat -tDisplay timestamps with the output

iostat

CommandDescription
iostatDisplay CPU and I/O statistics
iostat -xDisplay extended statistics
iostat -dDisplay device utilization statistics
iostat -cDisplay only CPU statistics
iostat -p ALLDisplay statistics for all devices and partitions

mpstat

CommandDescription
mpstatDisplay CPU usage
mpstat -P ALLDisplay CPU usage for all processors
mpstat 1 5Display CPU usage every second for 5 times

sar

CommandDescription
sarCollect and report system activity
sar -u 1 3Report CPU utilization every second for 3 times
sar -rReport memory utilization
sar -n DEVReport network statistics
sar -bReport I/O and transfer rate statistics

netstat / ss

CommandDescription
netstat -tulnList all listening ports
netstat -iDisplay network interfaces
netstat -rnDisplay routing table
netstat -sDisplay network statistics
ss -tulnList all listening ports (ss command)
ss -iDisplay network interfaces (ss command)
ss -rnDisplay routing table (ss command)
ss -sDisplay network statistics (ss command)

iftop (requires installation)

CommandDescription
iftopDisplay real-time network bandwidth usage
iftop -i interfaceDisplay network bandwidth usage for a specific interface
iftop -PShow ports
iftop -nShow numerical addresses rather than resolving hosts

tcpdump

CommandDescription
tcpdump -i interfaceCapture packets on a specific interface
tcpdump -n host hostCapture packets to/from a specific host
tcpdump -nn port portCapture packets on a specific port
tcpdump -w file.pcapWrite captured packets to a file
tcpdump -r file.pcapRead packets from a file

Important /proc Subdirectories and Files

Directory/FileDescription
/proc/cpuinfoDetailed information about the CPU, such as model, cores, and speed
/proc/meminfoDetailed information about memory usage
/proc/versionKernel version and build information
/proc/cmdlineKernel command line used to boot the system
/proc/devicesLists all character and block devices currently configured
/proc/diskstatsDisk I/O statistics
/proc/uptimeSystem uptime information
/proc/loadavgLoad average of the system
/proc/mountsMounted filesystems
/proc/partitionsInformation about disk partitions
/proc/swapsSwap space utilization
/proc/sysKernel tunable parameters (sysctl)
/proc/sys/kernelKernel-related parameters
/proc/sys/netNetwork-related parameters
/proc/netNetwork status information
/proc/interruptsNumber of interrupts per CPU per I/O device
/proc/iomemMemory map for the system
/proc/ioportsI/O port usage
/proc/modulesLoaded kernel modules
/proc/kallsymsKernel symbol table
/proc/kcorePseudo-file representing the physical memory of the system
/proc/slabinfoKernel slab allocator information
/proc/selfProcess-specific information for the current process
/proc/self/cmdlineCommand line of the current process
/proc/self/environEnvironment variables of the current process
/proc/self/exeSymlink to the executable of the current process
/proc/self/statusCurrent process status information
/proc/self/limitsResource limits of the current process
/proc/self/mountsMounts of the current process
/proc/self/cgroupCgroup membership of the current process
/proc/self/fdFile descriptors opened by the current process
/proc/self/fdinfoDetailed information about file descriptors
/proc/self/mapsMemory maps of the current process
/proc/self/smapsExtended memory maps of the current process
/proc/self/memMemory of the current process
/proc/self/taskTasks (threads) of the current process
/proc/[pid]/Information specific to process with PID
/proc/[pid]/cmdlineCommand line of the process with PID
/proc/[pid]/environEnvironment variables of the process with PID
/proc/[pid]/exeSymlink to the executable of the process with PID
/proc/[pid]/statusStatus information of the process with PID
/proc/[pid]/limitsResource limits of the process with PID
/proc/[pid]/mountsMounts of the process with PID
/proc/[pid]/cgroupCgroup membership of the process with PID
/proc/[pid]/fdFile descriptors opened by the process with PID
/proc/[pid]/fdinfoDetailed information about file descriptors of the process with PID
/proc/[pid]/mapsMemory maps of the process with PID
/proc/[pid]/smapsExtended memory maps of the process with PID
/proc/[pid]/memMemory of the process with PID
/proc/[pid]/taskTasks (threads) of the process with PID

MPV Hotkeys Cheatsheet

HotkeyDescription
SpaceToggle play/pause
fToggle fullscreen
mMute/unmute audio
9 / (Decrease volume
0 / )Increase volume
[Decrease playback speed
]Increase playback speed
{Halve playback speed
}Double playback speed
backspaceReset playback speed to normal
Left ArrowSeek backward 5 seconds
Right ArrowSeek forward 5 seconds
Up ArrowSeek forward 60 seconds
Down ArrowSeek backward 60 seconds
Shift+Left ArrowSeek backward 1 second
Shift+Right ArrowSeek forward 1 second
Ctrl+Left ArrowSeek backward 10 minutes
Ctrl+Right ArrowSeek forward 10 minutes
.Move forward one frame (pause required)
,Move backward one frame (pause required)
oShow file info
IShow codec info
qQuit
QForce quit (without saving the resume position)
sTake a screenshot
STake a screenshot without subtitles
Ctrl+sTake a screenshot and include the OSD
TToggle displaying time
Ctrl+oCycle through OSD (On-Screen Display) levels
vToggle subtitles
jCycle through subtitles
JCycle through secondary subtitles
#Toggle subtitle visibility
zAdjust subtitle delay backward
xAdjust subtitle delay forward
rRotate video
pToggle between current and previous subtitle track
lAdjust audio delay backward
kAdjust audio delay forward
Ctrl++Increase subtitle font size
Ctrl+-Decrease subtitle font size
Alt++Increase subtitle border size
Alt+-Decrease subtitle border size
Ctrl+rToggle random playback
Ctrl+shift+rToggle looping playback
Ctrl+pToggle playlist navigation display
Ctrl+uReload playlist
Ctrl+EnterToggle between fullscreen and windowed mode
EscExit fullscreen or close OSD menu
hSeek to the previous chapter
lSeek to the next chapter
yAdjust subtitle delay back by 0.1 seconds
YAdjust subtitle delay forward by 0.1 seconds
tToggle stay-on-top mode
Ctrl+fToggle autofit
Ctrl+cCopy current file path to clipboard
Ctrl+vPaste URL/file path from clipboard and open