My simple library

..of useful code



Chapters

Linux Cheat Sheet

1. System Information

Command Description Example
uname -a Show system and kernel information uname -a
lsb_release -a Display Linux distribution information lsb_release -a
cat /etc/os-release Show OS release information cat /etc/os-release
uptime Show system uptime and load average uptime
free -h Display memory usage (human-readable) free -h
df -h Show disk space usage df -h
du -sh [dir] Display directory size du -sh /home
top or htop Interactive process viewer htop

2. File System Navigation

Command Description Example
pwd Print working directory pwd
ls List directory contents ls -lah
cd Change directory cd /var/www
mkdir Create directory mkdir -p projects/new
rmdir Remove empty directory rmdir old_dir
touch Create empty file touch file.txt
cp Copy files/directories cp -r source_dir dest_dir
mv Move/rename files mv old.txt new.txt
rm Remove files/directories rm -rf directory
find Search for files find / -name "*.log"
locate Find files quickly (uses database) locate nginx.conf

File Permissions:

  • chmod 755 file - Change file permissions (owner: rwx, group: r-x, others: r-x)
  • chown user:group file - Change file owner and group
  • chgrp group file - Change file group
  • umask - Set default permissions for new files

3. File Viewing and Editing

Command Description Example
cat Display file contents cat file.txt
less or more View file page by page less large_file.log
head Show first lines of file head -n 20 file.log
tail Show last lines of file tail -f /var/log/syslog
grep Search text patterns grep "error" *.log
awk Pattern scanning and processing awk '{print $1}' file.csv
sed Stream editor for text substitution sed 's/old/new/g' file.txt
nano Simple text editor nano file.txt
vim or vi Advanced text editor vim /etc/hosts
diff Compare files line by line diff file1.txt file2.txt
wc Count lines, words, characters wc -l file.txt

4. Package Management (APT)

Command Description Example
sudo apt update Update package lists sudo apt update
sudo apt upgrade Upgrade installed packages sudo apt upgrade
sudo apt install Install a package sudo apt install nginx
sudo apt remove Remove a package sudo apt remove apache2
sudo apt purge Remove package with config files sudo apt purge mysql-server
sudo apt autoremove Remove unused packages sudo apt autoremove
sudo apt search Search for packages sudo apt search python3
sudo apt show Show package information sudo apt show nginx
sudo apt list --installed List installed packages sudo apt list --installed
sudo apt-get dist-upgrade Upgrade distribution sudo apt-get dist-upgrade
sudo apt-cache policy Show package version priorities sudo apt-cache policy nginx
sudo dpkg -i Install .deb package sudo dpkg -i package.deb
sudo dpkg -l List installed .deb packages sudo dpkg -l

Snap Commands:

  • snap find - Search for snaps
  • snap install - Install snap package
  • snap remove - Remove snap package
  • snap list - List installed snaps
  • snap refresh - Update snaps

5. Process Management

Command Description Example
ps Display running processes ps aux
top Interactive process viewer top
htop Enhanced process viewer htop
kill Terminate process by PID kill -9 1234
killall Terminate processes by name killall nginx
pkill Kill processes by pattern pkill -f "python script.py"
pgrep Find process IDs by name pgrep nginx
nice Run program with modified priority nice -n 10 command
renice Change priority of running process renice 5 -p 1234
nohup Run command immune to hangups nohup command &
bg / fg Move jobs to background/foreground bg %1
jobs List background jobs jobs
systemctl Control systemd services systemctl status nginx

Systemd Service Management:

  • systemctl start service - Start service
  • systemctl stop service - Stop service
  • systemctl restart service - Restart service
  • systemctl reload service - Reload config
  • systemctl enable service - Enable on boot
  • systemctl disable service - Disable on boot
  • systemctl status service - Check service status
  • journalctl -u service - View service logs

6. Networking

Command Description Example
ip addr or ifconfig Show network interfaces and IPs ip addr show
ping Test network connectivity ping google.com
traceroute Trace route to host traceroute google.com
netstat or ss Show network statistics ss -tulnp
dig or nslookup DNS lookup dig example.com
whois Domain WHOIS information whois example.com
wget Download files from web wget https://example.com/file.zip
curl Transfer data from URLs curl -O https://example.com/file
ssh Secure shell client ssh user@host
scp Secure file copy scp file.txt user@host:/path
rsync Remote file synchronization rsync -avz /local user@host:/remote
ufw Uncomplicated firewall sudo ufw allow 22/tcp
iptables Packet filtering framework sudo iptables -L
nmcli NetworkManager command line nmcli device status
hostname Show or set system hostname hostname -I

Network Troubleshooting:

  • mtr - Network diagnostic tool (combines ping + traceroute)
  • telnet - Test TCP port connectivity
  • nc or netcat - Network swiss army knife
  • tcpdump - Network packet analyzer
  • iptables -A INPUT -p tcp --dport 8000 -j ACCEPT - For opening the incoming traffic
  • iptables -A OUTPUT -p tcp --dport 8000 -j ACCEPT - For opening the outgoing traffic
  • netfilter-persistent save - Save the added rules so that the new rules will be applied even after a server reboot
  • service iptables save - Save the added rules so that the new rules will be applied even after a server reboot

7. Archives and Compression

Command Description Example
tar Archive files (tape archive) tar -cvf archive.tar files/
gzip Compress files (.gz) gzip file
gunzip Decompress .gz files gunzip file.gz
bzip2 Compress files (.bz2) bzip2 file
bunzip2 Decompress .bz2 files bunzip2 file.bz2
zip Package and compress files (.zip) zip archive.zip files/
unzip Extract .zip files unzip archive.zip
7z High compression ratio archiver 7z a archive.7z files/

Common Combinations:

  • Create tar.gz: tar -czvf archive.tar.gz files/
  • Extract tar.gz: tar -xzvf archive.tar.gz
  • Create tar.bz2: tar -cjvf archive.tar.bz2 files/
  • Extract tar.bz2: tar -xjvf archive.tar.bz2
  • View tar contents: tar -tvf archive.tar

8. User and Permission Management

Command Description Example
sudo Execute command as superuser sudo apt update
su Switch user su - username
useradd Add new user sudo useradd -m username
usermod Modify user account sudo usermod -aG sudo username
userdel Delete user sudo userdel -r username
passwd Change user password passwd username
groupadd Add new group sudo groupadd groupname
groups Show user groups groups username
id Show user and group info id username
who or w Show logged in users w
last Show last logged in users last

9. System Monitoring and Logs

Command Description Example
dmesg Kernel ring buffer messages dmesg | grep error
journalctl Systemd journal logs journalctl -xe
tail -f Follow log file in real-time tail -f /var/log/syslog
vmstat System performance monitoring vmstat 1
iostat CPU and I/O statistics iostat -x 2
sar System activity reporter sar -u 1 3
lsof List open files lsof -i :80
strace Trace system calls strace -p 1234
ncdu Disk usage analyzer ncdu /
glances Advanced system monitoring glances

Important Log Files:

  • /var/log/syslog - General system activity
  • /var/log/auth.log - Authentication logs
  • /var/log/kern.log - Kernel messages
  • /var/log/dmesg - Boot-time kernel messages
  • /var/log/nginx/ - Nginx web server logs
  • /var/log/apache2/ - Apache web server logs

10. Scripting and Automation

10.1 Basic Bash Script

#!/bin/bash
# Simple backup script
BACKUP_DIR="/backups"
DATE=$(date +%Y-%m-%d)
SOURCE="/var/www"

# Create backup directory if not exists
mkdir -p $BACKUP_DIR

# Create compressed tar archive
tar -czf "$BACKUP_DIR/backup_$DATE.tar.gz" "$SOURCE"

# Delete backups older than 30 days
find $BACKUP_DIR -type f -name "*.tar.gz" -mtime +30 -delete

echo "Backup completed: $BACKUP_DIR/backup_$DATE.tar.gz"

10.2 Common Scripting Elements

Element Description Example
#!/bin/bash Shebang line (specifies interpreter) #!/bin/bash
Variables Store values NAME="John"
$1, $2, ... Positional parameters echo "Hello $1"
if [ condition ] Conditional statement if [ -f "$FILE" ]; then ...
for Loop through items for FILE in *.txt; do ...
while Loop while condition is true while [ $COUNT -lt 10 ]; do ...
functions Define reusable code blocks function greet() { echo "Hello $1"; }
exit Exit script with status code exit 0

10.3 Cron Jobs (Scheduled Tasks)

# Edit crontab file
crontab -e

# Example entries
* * * * * /path/to/script.sh        # Run every minute
0 * * * * /path/to/script.sh        # Run hourly at :00
0 0 * * * /path/to/backup.sh        # Run daily at midnight
0 0 * * 0 /path/to/cleanup.sh       # Run weekly on Sunday
0 0 1 * * /path/to/report.sh        # Run monthly on 1st

Cron Time Format:

* * * * * command

  1. Minute (0-59)
  2. Hour (0-23)
  3. Day of month (1-31)
  4. Month (1-12)
  5. Day of week (0-7, where both 0 and 7 are Sunday)

11. Security

Command Description Example
sudo Execute command as another user sudo visudo
chmod Change file permissions chmod 600 private.key
chown Change file owner chown user:group file
passwd Change user password passwd username
ssh-keygen Generate SSH key pair ssh-keygen -t rsa -b 4096
gpg GNU Privacy Guard encryption gpg --encrypt file.txt
fail2ban-client Ban IPs with too many failed attempts fail2ban-client status sshd
clamscan Virus scanner clamscan -r /home
lynis Security auditing tool sudo lynis audit system
openssl SSL/TLS toolkit openssl req -new -newkey rsa:2048 -nodes -keyout server.key -out server.csr

Security Best Practices:

  • Always use sudo instead of logging in as root
  • Disable root SSH login (PermitRootLogin no in /etc/ssh/sshd_config)
  • Use SSH keys instead of passwords
  • Keep system and packages updated (sudo apt update && sudo apt upgrade)
  • Configure firewall (ufw or iptables)
  • Change owner to 'myuser' sudo chown myuser myfile.txt
  • Change owner to 'myuser' and group to 'notmygroup' sudo chown notme:notmygroup myfile.txt
  • Change owner to 'myuser' and group to 'notmygroup' sudo chown notme:notmygroup myfile.txt
  • Use usermod to change user's settings such as group, password and more
  • Create a new group sudo groupadd demo
  • Add user to group sudo usermod --append --groups demo user1
  • Remove user from group sudo gpasswd --delete user1 demo
  • Delete a group sudo groupdel demo

chmod tutorial:

  • 4 = read, 2 = write, 1 = execute, 0 = no permission
  • 7 = 4 + 2 + 1, 5 = 4 + 0 + 1, 4 = 4 + 0 + 0
  • Equivalent commands (chmod u=rwx,g=rx,o=r myfile or chmod 754 myfile)
  • Use -R to affect all folders and files it contains
  • Regularly check system logs for suspicious activity

12. Miscellaneous Useful Commands

Command Description Example
alias Create command shortcuts alias ll='ls -alF'
history Show command history history | grep apt
!! Repeat last command sudo !!
man Show manual pages man ls
whatis Brief command description whatis grep
which Show full path of commands which python
whereis Locate binary, source, and manual pages whereis java
watch Execute program periodically watch -n 1 free -h
time Measure command execution time time ls -R /
cal Display calendar cal -3
bc Arbitrary precision calculator echo "5+7" | bc
shutdown Shutdown or restart system sudo shutdown -r now
reboot Reboot system sudo reboot