Command Line Linux Tips and Tricks

Create a sudo user

# usermod -aG sudo username

Compress a directory

tar -zcvf file-name.tar.gz directory-name


zip -r directory-name

Uncompress a tar.gz file

tar -zxvf compress-file.tar.gz

Uncompress .gz file

gunzip compress-file.gz


gzip -d compress-file.gz

List the last modified files in a specific directory recursively

Find the last 10 modified files from a certain directory recursively:

find . -type f -printf '%T@ %p\n' | sort -k1,1nr | head -10

List all files older than x days recursively

Find the files older than 15 days in the current directory and subdirectories:

find . -type f -mtime +15

If you want to delete the files:

find . -type f -mtime +15 -delete

List all files newer than x days recursively

Find the files newer than 15 days in the current directory and subdirectories:

find . -type f -mtime -15

Recursively Search All Files For A String

Find all the files that contain the «foo» string in the current directory and in its subdirectories:

grep -ri -l "foo" .

Recursively renaming part of a filename

Rename recursively a part of a file name (ABC) with the XYZ text.

$ find . -name '*ABC*' -exec rename 's/ABC/XYZ/' {} \;

Print a file, excluding comments and blank lines

grep "^[^#;]" file
grep -v '^$\|^\s*\#' file

To see the crontab

grep -v '^$\|^\s*\#' temp

To remove the time configuration in each line (to copy and paste the crontab commands to the console)

crontab -l | grep -v '^$\|^\s*\#' | cut -d" " -f6-

Restore a MySQL database with different name

First I have to create the backup from the old_database_name

mysqldump -uroot -p --routines --triggers old_database_name > database_backup.sql

Then I have to restore the backup in a new database: new_database_name

mysql -uroot -p -A -Dnew_database_name < database_backup.sql

Create a compressed MySQL dump and restore it

mysqldump -uroot -p databaseName | gzip > databaseName.sql.gz
gunzip databaseName.sql.gz |  mysql -u root -p databaseName

Delete commented or empty lines in a file

sed -i '/^[@#]/ d' file.txt
sed -i -rn '/\S/p' file.txt

Execute a command each X seconds

Execute «ls | wc -l» each 5 seconds

watch -n 5 "ls | wc -l"

Symbolic link

ln -s origin destination

ln -s /etc/nginx/sites-available/ /etc/nginx/sites-enabled/

Get The Process Start Time And Date

ps -eo pid,lstart,cmd


Add an IP to the whitelist

$ iptables -A INPUT -s IPv4 -j ACCEPT