Recopilación de comandos de consola Linux
14 minutos de lectura
[ Editado por última vez: 05/06/2022 ]
Con los años he ido acumulando una lista creciente de comandos Linux para hacer cosas de todo tipo, como administración del servidor apache, manipulación de imágenes, y un largo etcétera. Normalmente lo tengo guardado en un correo que tengo en la bandeja de "Borradores", pero hoy he creído que era mejor tenerlo publicado en línea y así tal vez ser útil a otros.
Iré actualizando este artículo a medida que descubra nuevos comandos.
FILE MANAGEMENT
file list
You can paginate results adding | pg
or | less
to the end.
count files in a directory
More info about symbolic files, subdirectories, etc... here.
Find files not matching a regex query
Enable the use of regex pattern list:
Use extglob to list/remove/etc the files who don't match a list of regex pattern:
rm -la !(*190802*|*zip)
Disable extglob OPTNAME:
find any file by name
space occupied by a whole directory
remove a directory including subdirectories and files inside
create symbolic link
rsync
creating/editing/assigning GROUPS of users
sudo usermod -a -G gitwww sergi
sudo usermod -a -G gitwww www-data
sudo usermod -a -G gitwww root
sudo usermod -a -G gitwww apache
sudo chgrp -R gitwww /var/www/suntransfers-new
sudo chgrp -R gitwww .
To compress the current directory, including all subdirectories into the archive file
To compress a directory excluding a list of files/directories:
To unzip in the current directory
recursively find the last 500 modified files, sorted by change-time
to list store drives and their available space
full emptied of the user trash (Ubuntu)
We only need install the first time:
Afterwards we use this command:
To empty System logs (because problem of space)
cat /dev/null > /var/log/syslog
cat /dev/null > /var/log/kern.log
calculate de SHA sum of a file
copy all the content of a directory
Recursive copy of all the directories and files, even the hidden ones:
delete only files in a directory & subdirectories
change permissions of only some subdirectories
In this example we filter the subdirectories inside /path beginning with "some_" and not recursively searching inside subdirectories:
[2020-dic] easy encrypt/decrypt with symmetric key
To encrypt:
To decrypt:
In both tasks (encrypt/decrypt) the prompt will ask you for the symmetric key.
[2022-jun] reduce size of a PDF of several pages
Problem: some users upload to server a PDF containing one or more innecesary big images. Solution: to convert first each page to an optimized JPG image, and then build a new PDF file with those JPG images.
Firs we need install Poppler-utils and ImageMagick:
sudo apt install imagemagick
You probably will need modify Imagemagick security policies:
Replace this:
with this:
Finally, this will generate a JPG file for each page on the PDF:
this will join JPG pages in a new PDF:
MULTIMEDIA
Config the miniDLNA for read to an auto-mount partition (usually external)
Create the folder /media/sergi/hp from root user:
Create a bash file (minidlna_autostart) for mount & restart minidlna:
mount -t ntfs-3g /dev/sda6 /media/hp
service minidlna restart force-reload
Execute this bash file from the autostart of the Preferences/LXSession
Edit this config file:
and set:
media_dir=V,/media/hp/__PELIS__
cat /var/log/minidlna.log
add a subtitle stream to an mp4 movie
FFMPEG
Convert an audio file from OGG to MP3:
Convert an audio file from MP3 to WAV:
Accelerate the speed of a movie 1.5 times, generating a new file:
Extract de audio (mp3) of a video file (flv, mp4, mkv...):
Note: use 0-10 values on -q:a 10 to control quality (more is less).
YOUTUBE-DL
Show a list of downloable formats of a same Youtube video:
Download an specific format (249):
To know the font types used in a GIMP image file (xcf)
Webcam streaming on local LAN using VLC
Command for server machine to detect video device:
It returns usually:
Begin streaming from server machine:
View video streaming on client machine (put your IP, instead):
Join multiple videos in a unique file MKV
Build a video-files.txt with the list of files to join:
file 'bar.mp4'
file 'foo bar.mp4'
Run this simple command:
How to convert MONO audio to STEREO audio from a Gnome SimpleScreenRecorder video
If the audio channel containing only SILENCE is the c0 then we use this settings to populate it with an exact copy of the audio channel c1:
APACHE SERVER
enable .htaccess logging (MOD_REWRITE)
Put this line inside Directory node on a virtual host configuration file (/etc/apache2/available-sites/barllo.me.conf):
Note: 2 is the level of trace... can be from 1 to 8.
301 redirection of a whole website to a new domain
RewriteRule ^(.*)$ http://elportalweb.de/tonytambor/$1 [R=301,L]
add the "official" repository
sudo apt-get update
install on php7 missing pieces from php5
PHP7, solve error "Call to undefined utf8_decode()"
solution for: Call to undefined function mcrypt_decrypt()
sudo php5enmod mcrypt
sudo service apache2 restart
install PDO for SQLite
sudo service apache2 restart
install imagick & GD
Apache css/javascript cache
sudo apachectl restart
restart apache
sudo service apache2 restart (ubuntu)
vhosts in centos
cPanel MIME types for be compressed by Apache automatically
clean RAM cache
use a directory on another drive or partition using a symlink
it's not enough with create a symbolic link. The magic comes curiously when we change the execution permissions
chmod -R o+x "/media/sergi/PARTITION_NAME/path_to/source_dir"
chmod o+x "/media/sergi/PARTITION_NAME/path_to"
sudo chmod o+x "/media/sergi/PARTITION_NAME"
Create a new VHOST duplicating another one
sudo gedit /etc/apache2/sites-available/example2.com.conf
sudo a2ensite example.com.conf
sudo service apache2 restart
sudo gedit /etc/hosts
And add something like this:
127.0.1.1 www.example2.me
To list loaded PHP.ini files location
It returns something like:
Loaded Configuration File: /etc/php/7.1/cli/php.ini
Scan for additional .ini files in: /etc/php/7.1/cli/conf.d
Additional .ini files parsed: /etc/php/7.1/cli/conf.d/10-mysqlnd.ini,
/etc/php/7.1/cli/conf.d/10-opcache.ini,
/etc/php/7.1/cli/conf.d/10-pdo.ini,
/etc/php/7.1/cli/conf.d/15-xml.ini,
/etc/php/7.1/cli/conf.d/20-calendar.ini,
/etc/php/7.1/cli/conf.d/20-ctype.ini,
...
Run Apache with your user, when using ecryptfs
I needed it when i encrypted my home dir (with ecryptfs) and i put there www directory. You need to edit this file:
And replace the values of this:
export APACHE_RUN_GROUP=myusername
And restart Apache:
MYSQL SERVER
empty database / delete all tables from database
CREATE DATABASE mydbname;
CREATE DATABASE mydbname CHARACTER SET='utf8mb4' COLLATE='utf8mb4_general_ci';
download a dump of the database
tar -czf travelgroup_qa.dump.tar.gz travelgroup_qa.dump (generate tar.gz --- execute from server)
rm -f -r travelgroup_qa.dump (delete dump --- execute from server)
scp root@suntransfers.com:suntransfers_2014_12_18_12_54.sql.gz . (download --- execute from local, put attention on the FINAL DOT of this command!!!)
gzip -d suntransfers_2014_12_18_12_54.sql.gz (extract sql dump from zip file --- execute from local)
mysql -u root -p travelgroup-master < travelgroup_qa.dump (import dump --- execute from local)
make duplicated of a database from linux shell
echo "create database `duplicated_db`" | mysql -u username -p
mysql -u username -p duplicated_db < db.dump
connect
use my_database_name (for select a database)
restart mysql in centos (QA server)
list of tables with a lot of columns with its properties!
SHOW TABLE STATUS WHERE true;
SHOW PROCESSLIST;
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('id_trayecto','trayecto_id','id_route','route_id')
AND TABLE_SCHEMA='travelgroup';
disable temporally the check of integrity for foreign keys and be able to drop tables
drop table if exists `refund_reasons`;
SET FOREIGN_KEY_CHECKS=1;
make a dump
duplicate a table and its content
Create a new user and its privileges
flush privileges;
List users with access to a database
Reset password to mysql root user
Stop the MySQL Server:
Start the mysqld configuration:
In some cases, you've to create the /var/run/mysqld first:
Login to MySQL as root (maybe you need to try twice !?):
Execute these mysql commands:
FLUSH PRIVILEGES;
exit;
Note: on some versions, if password column doesn't exist, you may want to try:
OTHER SYSTEM TOOLS
work as root user
Create new user
sudo passwd {username}
Give root privileges to this user:
network tools
lspci | egrep -i --color 'network|ethernet' (list network interfaces)
control brigthness in Lubuntu
or
or
to send output of a command though email
create/share a ssh-key
To generate a pair private/public key on your local:
To store this identification on your remote:
show network traffic monitor on console
sudo tcptrack -i eth0
disable Teamviewer daemon
to burn bootable ISO image to an USB drive
Easy command for make a bootable USB from an ISO file:
set spanish keyboard
disable touchscreen on startup
You must add this command to the startup app list:
To migrate IMAP messages
Very useful command for pass ALL the email messages & folders from a server to other, usually during a server migration:
Note 1: add --dry --justfolders
to check (without changes) the correct mapping of the folders.
Note 2: so, usually one of the hosts is an IP (note: the IP of the mail server USUALLY is not the same of the web server IP!). Sometimes the recommendation is not to set port neither ssl/tls settings. The imapsync script is enough smart to test some typical connection settings by himself if you don't specify those settings.
Clone a remote directory using FTP
To make a perfect recursively clone of a remote directory, including hidden files/directories:
To generate a private/public key pair
To upload a SSH key to login on server
To kill teamviewer process and avoid future auto-boot
To avoid future autoboot execution:
To "kill" process (to stop daemon):
Basic tasks with CRONTAB
To edit crontab file for current user:
To add a new crontab file to a user:
sudo crontab -u www-data cron.tmp
rm cron.tmp
To check the last executions of ALL crontabs:
Upload a local file to server using SSH
You must run a command like this from your local terminal
Download a remote file to local using SSH
You must run a command like this from your local terminal
If you get an error related to permission denied, try this:
Anyway, you must be sure than the user remoteuser has read permission over that file on server.
If any of the paths contain spaces, use this:
[2020] Increase font size on terminal
On terminal run this command to edit console setup:
Once inside, change the font size:
[2020] Disable some hardware on boot (touchscreen, built-in webcam...)
Using this command i found that my webcam (which use driver uvcvideo) is on the Bus X and Device Y:
And in the output of this other command i find that the vendorID and productID of the device and those Bus X & Device Y is something like 0bda:573d:
So now i add this new rule (file):
and i put inside this:
[2020] Send email from terminal with subject and body
Whenever we have installed and configured an email server like exim, usually on an VM. Thern we can do it with a single terminal command line, breaking lines with \n
.
It's necessary to delimiter string content with single quote, not double quote:
[2020-nov] Useful network/wifi CLI-tools
Info about all netowrk interfaces (IP, type,...):
Graphical list of all wifi access points and their quality
Graphical list of all wifi access points and their quality
[2020-dic] Migrate a whole server between two VM's using scp/ssh
Use the next command when you need to "move" all your server (settings, databases, mail... almost all) from a VPS to another one. You must have installed the same OS version on both machines. From the terminal connected to the origin machine run this:
[2021-feb] Get details of a PID process
[2021-sep] Deactivate/activate a built-in wifi device
To know the name of the network device to be deactivated:
To deactivate the use of a device:
To re-activate it:
[2022-apr] Run an installed flatpak app
flatpak run org.flameshot.Flameshot gui
With this command you get the list of installed flatpak apps and its "name":
[2022-mai] Customize keyboard map layout on X11 to add foreign symbols
In this example i want to render "ç" when pressing ALTGR+c in a latam keyboard:
There you must edit this line, putting "ccedilla" instead of "cent" and "copyright":
And then reload keyboard layout with:
[2022-oct] Useful keyboard shortcuts on GNOME
Open capture GUI of flameshot (installed via Flatpak):
Temporally suspend ubuntu:
[2023-mar] Start SSH server on boot
To check the status:
Añada su comentario: