LS
List all items in a directory:
ls
List (a)ll items in a directory, including hidden ones:
ls -a
List all items in a directory in (l)ong list format with + info:
ls -l
List all items in a directory, size in (h)uman readable format:
ls -h
List all items starting with the newest by (t)ime:
ls -t
We can combine those options:
ls -la / ls -lh / ls -ah / ls -alht
List items in another directory:
ls /another/folder/
List all items sorted by (S)ize (3-2-1):
ls -S
but we add h and l to make it easier to read ls -Slh
List all items sorted by size (r) (1-2-3):
ls -Slhr
List all items sorted by size (1-2-3) divided by their subfolders:
ls -SlhrR / ls -SlhR
Copy the result of the command into a TXT file:
ls -alh > ~/Documents/listing.txt
Access the LS manual to see more options:
man ls
CD
Got to another directory:
cd /folder/where/i/want/to/go/
Go back to the home directory:
cd / cd ~ / cd -
Go to the upper folder level:
cd ..
Change folder by indicating absolute path with upper level:
cd ../../etc/ssh/
TOUCH
Allows to modify the access and modification date of a file, but can be used to create files.
user@my-pc:$ touch file.txt
RM
Permite borrar archivos. Con la opción "-v" de Verbose, veremos confirmación de la acción.
user@my-pc:$ touch file1.txt
user@my-pc:$ rm -v file1.txt
removed ' file1.txt'
MKDIR
Permite crear carpetas y con la opción "-p" podemos crear arboresencia de carpetas.
user@my-pc:$ mdkir -p dir1/dir2/dir3/
user@my-pc:$ ls -R dir1/
dir1/:
dir2
dir1/dir2:
dir3
RMDIR
Permite borrar una o varias carpetas pero sólo funciona si están vacías.
user@my-pc:$ mkdir dir2
user@my-pc:$ rmdir dir2
user@my-pc:$ mkdir dir1/
user@my-pc:$ touch file.txt dir1/
user@my-pc:$ rmdir dir1/
rmdir: failed to remove 'dir1/': Directory not empty
El comando "rm dir1/" tampoco funcionará ya que está orientado a archivos exclusivamente.
añadimos -r de Recursive para borrar:
user@my-pc:$ rm -r dir1/
MV
Permite mover archivos pero usado también para cambiar nombres de archivos.
Cambiar nombre:
user@my-pc:$ touch file1.txt
user@my-pc:$ mv file1.txt file2.txt
Desplazar archivo:
user@my-pc:$ mv file2.txt ../otra/carpeta/CP
Permite hacer una copia de archivos.
user@my-pc:$ touch file1.txt
user@my-pc:$ cp file1.txt file1-backup.txt
user@my-pc:$ ls -l
-rwxrwxrwx 1 blm blm 120 Nov 7 10:54 file1.txt
-rwxrwxrwx 1 blm blm 120 Nov 7 10:54 file1-backup.txt
Hay una opción para hacer copias de seguridad:
user@my-pc:$ cp --backup -r dir1/ dir1-backup
Pero es muy importante enviar la opción "p" (persevere) para mantener los permisos de origen ya que si la carpeta/archivos son del usuarioA y hacemos backup como root, el backup será de root, pero poniendo la p, permanecerá del usuarioA. Podemos agregar la "v" de "verbose" para ver el detalle de las acciones emprendidas:
user@my-pc:$ cp -rv dir1/ dir-copy
'dir1' -> 'dir-copy'
user@my-pc:$ rm -rv dir-copy/
CAT
Permite leer todo el archivo en pantalla (cuidado con archivos muy grandes), podemos cancelar con CTRL-C
user@my-pc:$ cat file1.txt
1
2
3
4
5
6
TAC
Allows you to read the whole file on the screen upside down (be careful with very large files), we can cancel with CTRL-C
user@my-pc:$ tac file1.txt
6
5
4
3
2
1
LESS
It allows us to see the content of a file in a paginated way, it places us at the beginning and with the arrows we can continue reading the rest of the file
(view definition from this article)
"Both more and less commands allow pagination of large text files. When perusing large
files, it is not always possible to use grep unless we know an exact string to search.
So we
would
want to use either more or less.
Typically, less is the preferred choice, as it allows both forward and backward
perusal of paginated text"
MORE
To be done
xxxxxxxx
HEAD
Allows to display the beginning of a file, first 10 lines only by default.
user@my-pc:$ head -50 archivo.log
(see the first 50 lines of the file)
TAIL
Permite mostrar el final de un archivo, las 10 primeras lineas únicamente por defecto.
user@my-pc:$ tail -20 archivo.log
(ver las últimas 20 lineas del archivo)
Si añadimos "-f" como opción, mientras está abierto el archivo, se actualiza en directo.
user@my-pc:$
WC
Permite contar (Word Count) el número de lineas, palabras y carácteres que hay en un archivo.
user@my-pc:$ wc archivo.txt
88 1005 7345 archivo.txt
Detalle:
88 = lineas
1005 = palabras
7345 = carácteres
NANO
I want to edit a file using the Nano editor:
sudo nano myfile.txt
Save changes to my file:
CTRL + o
Exit the file:
CTRL + x
DF
Allows to view mounted systems and sizes:
df
Convert Bytes to TB,GB,MBR:
df -h
View the type of format used:
df -T
DU / LSBLK / BLKID / FDISK /
View the size of a directory and subdorectories:
du
View the size of another directory and subdirectories:
du Downloads/
View the size one directory without subdirectories:
du -s
and we can also add "h"
du -sh Downloads/
Change the format of sizes to GB, MB:
du -sh
View the total size of the content:
du -shc
View disk usage & partitions
lsblk
What USB devices are connected on my machine?:
lsusb
or: sudo fdisk -l
TAR
how to make a tar.gz file of a folder:
tar -zcf my-filename.tar.gz which-folder/here-it-is/
how to make a tar.gz file with date of action:
tar -zcf my-filename-$(date +%Y-%m-%d).tar.gz which-folder/here-it-is/
FIND
Find and delete files older than 7 days
find path/to/folder/* -mtime +7 -delete
Remove one or more programs with DPKG
sudo dpkg -r htop alien
TREE
View the full tree of directories and subdirectories:
tree
Like with LS we can add the "h" option:
tree -h
FILE
View the type of file:
file example.txt
user@pc:$ example.txt: ASCII text
SCP
It is CP over SSH to copy a files/directories:
- From your local system to a remote system.
- From a remote system to your local system.
- Between two remote systems from your local system.
Copy file to new folder on the same PC:
scp /home/user/docs/file1.txt /home/user/docs/newfolder/
Copy folder content from folder1 to folder2:
scp -r /home/user/docs/folder1/ /home/user/docs/folder2/
Copy files from PC to server over SSH:
scp -P 1234 /from/this/folder/file.txt user@192.168.1.10:/dest/folder/new-filename.txt
Copy folder from server to PC over SSH:
scp -P 1234 -r user@192.168.1.10:/home/user/from-this-folder/ /home/user/destinatation-folder/
RSYNC
Structure is always /SOURCE/ /DESTINATION/
Rsync folder from PC to remote via SSH:
rsync -a /home/folder user@111.222.233.44:/dest/folder/
Rsync with delete on destination the non existing files in source:
rsync -a --delete /home/folder user@111.222.233.44:/dest/folder/
Rsync with different port than 22:
rsync -rte 'ssh -p 1234' user@111.222.233.44:/home/user1/folder/ /home/user/dest-folder/
Rsync with "dry-run" (test before doing the task):
for d in rsync dest1/ dest2/
do rsync -avzr --dry-run --delete source/ $d
done
USERS & GROUPS
Create a new user:
sudo adduser user
Modify a new user:
sudo usermod user
Delete a user:
sudo userdel user
Delete user with all his files:
sudo userdel --remove-all-files user
Add user to the sudo group:
sudo usermod -aG sudo user
Create a new group:
sudo groupadd groupname
Modify a group:
sudo groupmod groupname
Delete a group:
sudo groupdel groupname
Change to the new user account:
su - user
Quit this user:
exit
Delete this user:
sudo userdel user / sudo userdel -r user
SSH
Connect via SSH to a distant machine:
ssh user@192.168.1.10
Connect via SSH to a distant machine through a specific port:
ssh user@192.168.1.10 -p 9999
Check if the SSH service is running:
sudo systemctl status sshd.service
Logout from an SSH connection:
exit
Change SSH default port:
sudo nano /etc/ssh/sshd_config
Restart SSH service to use the new port:
service sshd restart /or/
systemctl restart sshd.service
Error when login:
"Unable to negotiate with 192.168.8.109 port 22: no matching host key
type
found. Their offer: ssh-dss
We have to add this before the ssh login:
-oHostKeyAlgorithms=+ssh-dss
-oHostKeyAlgorithms=+ssh-dss ssh user@192.168.1.1
NETPLAN
Setup static IP Ethernet:
sudo nano /etc/netplan/00-installer-config.yaml
Setup static IP Wifi:
sudo nano /etc/netplan/00-installer-config-wifi.yaml
Structure of the YAML file:
# This is the network config written by 'subiquity'
network:
version: 2
wifis:
wlxf832e4b4e9b8:
access-points:
My-wifi-newtowrk:
password: mypassword
dhcp4: false
addresses:
- 192.168.1.25/24
nameservers:
search: [mydomain, otherdomain]
addresses: [10.10.10.1, 1.1.1.1]
routes:
- to: default
via: 192.168.1.1
System management
I want to update the programs on my machine:
sudo apt update
I want to upgrade the programs on my machine:
sudo apt upgrade
I want to upgrade the programs on my machine and pre-validate:
sudo apt upgrade -y
I want to do both in one command:
sudo apt update && sudo apt upgrade -y
Check the version of the kernel:
uname -srm
Reboot computer now
sudo reboot
Turn off computer (1min timer by default)
sudo shutdown
Turn off computer now
sudo shutdown -h now
Turn off computer in 1 day
sudo shutdown -h now
Expand Disk space
Extend Ubuntu Server filesystem 5Gb:
sudo lvextend --resizefs -L +5G ubuntu-vg/ubuntu-lv
Extend Ubuntu Server filesystem to all availabe:
sudo lvextend --resizefs -l +100%FREE ubuntu-vg/ubuntu-lv
Uptime & set timezones
View Uptime of the computer/server:
uptime
add -p for better understanding/readability:
uptime -p
View time and date on the machine:
timedatectl
Set NTP
timedatectl set-ntp yes
List Timezones;
timedatectl list-timezones
Set new timezone:
timedatectl set-timezone Europe/Madrid
Various
Too much information on my screen:
clear
or CTRL+L
Too much history of commands, delete them:
history -c
Delete ALL the history of commands:
rm ~/.bash_history
Check the version of the system:
lsb_release -a
with less info:
lsb_release -d
or:
cat /etc/os-release
Show content/part of a file:
cat my-file.txt
Download a file from a URL (linux kernel for ex.):
wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.19.4.tar.xz
Convert packages from .deb to .rpm or vice-versa
sudo apt install alien
sudo alien --to-rpm htop_3.0.5-7_amd64.deb
sudo alien --to-deb htop_3.0.5-7_amd64.rpm
Debian repository generator - /etc/apt/sources.list
https://debgen.xyz/
VERIFY INFO WITH TUTORIAL
Manage BOINC
Install the client:
sudo apt-get install boinc-client
Edit the config file to allow remote hosts to manage it:
sudo nano /var/lib/boinc-client/remote_hosts.cfg