UNIX Cheatsheet


ls / find


Find biggest files :

find <folder> -type f -exec du -Sh {} + | sort -rh | head -n <number_of_results>
find . -type f -exec du -Sh {} + | sort -rh | head -n 20

Find biggest directories :

# Top-level only
du -hs * | sort -rh | head -<number_of_results>
du -hs * | sort -rh | head -20

# Recursive, will have duplicate entries from subdirectories
du -a <search_root> | sort -n -r | head -n <number_of_results>
du -a . | sort -n -r | head -n 20

Delete all files older than 30 days :

find <folder> -mindepth 1 -mtime +30 -delete


sed / grep


Find first line matching a pattern in a file :

sed '/<pattern>/!d;=;Q' <file>>

Cut a slice of a file, between 2 given line numbers :

sed -n '<first_line>,<last_line>p;<last_line_plus_1>q' <input_file> > <output_file>


tar / zip


tar :

tar -cvf <archive.tar> <folder_to_archive>
tar -zcvf <archive.tar.gz> <folder_to_archive>

untar :

tar -xvf <archive.tar> (-C <destination_folder>)
tar -zxvf <archive.tar.gz> (-C <destination_folder>)

List files inside archive :

tar –tf <archive.tar>
tar –tzf <archive.tar.gz>
unzip -l <archive.zip>


Rsync


Copy from local to remote :

rsync -avzh -e ssh <local_folder> <user>@<host>:<remote_folder_or_file>

Copy from remote to local :

rsync -avzh -e ssh <user>@<host>:<remote_folder_or_file> <local_folder>

Copy a local folder while excluding some files/subfolders :

rsync -av --exclude=node_modules --exclude=.git <root_folder> <destination_folder>

Useful options

Dry-run :

--dry-run

Show progress while running :

--progress

Include or exclude some files from the target folder :

--include='*.txt'
--exclude='*.git'

Delete the target file if it already exist :

--delete

Delete the source file after successful transfer :

--remove-source-files

Delete all remote file in target folder that were not present in the source local folder :

--delete-after

Limit bandwidth :

--bwlimit=<size_in_kbps>


Fresh install


Setup root password :

sudo passwd root

Create a new user and its /home directory :

sudo useradd -m test

Add SSH keys :

sudo mkdir /home/<user>/.ssh
sudo nano /home/<user>/.ssh/authorized_keys

Change the default shell to bash :

sudo chsh -s /bin/bash <user>


iptables


List all rules in a proper table :

iptables --list

List all rules commands :

iptables -S

Save current config to disk :

iptables-save

Whitelist a specific IP adress :

iptables -A INPUT  -s 1.2.3.4 -p tcp -j ACCEPT
iptables -A OUTPUT -d 1.2.3.4 -p tcp -j ACCEPT

Whitelist a specific port :

iptables -A INPUT  -p tcp -m tcp --dport 2022 -j ACCEPT
iptables -A OUTPUT -p tcp -m tcp --dport 2022 -j ACCEPT


Misc


List all crontabs for all users :

for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done