Terminale di Linux

Terminale di Linux Terminale di Linux
Terminale di Linux

Terminale di Linux

Cos'è il terminale?

Il terminale è un'interfaccia testuale che ti permette di comunicare direttamente con il sistema operativo digitando comandi. A differenza dell'interfaccia grafica (mouse, finestre, icone), qui si scrivono istruzioni precise.

Terminologia corretta

Termine Significato
Terminale Il programma finestra che mostra il prompt (es. GNOME Terminal, Konsole, xterm)
Shell L'interprete dei comandi (es. bash, zsh, fish)
Console Storicamente il terminale fisico, oggi sinonimo di terminale
Prompt Il testo che aspetta un comando, es. $ (utente normale) o # (root)

Shell più comuni

Shell Caratteristiche Default su
bash Standard, onnipresente, scripting potente Ubuntu, Debian, RHEL, Fedora
zsh Autocompletamento avanzato, plugin, temi macOS, Kali Linux
fish Suggerimenti interattivi, configurazione facile - (installabile)
dash Leggera, veloce, POSIX-compliant Debian/Ubuntu per script di sistema

Come aprire il terminale

Distribuzione Scorciatoia Metodo alternativo
Ubuntu Ctrl + Alt + T Cerca "Terminal" nel menu
Linux Mint Ctrl + Alt + T Menu → Terminale
Fedora Ctrl + Alt + T Attività → Terminal
Pop!_OS Super + T Dock → Terminal
Qualsiasi Ctrl + Alt + F3 (TTY puro, senza GUI) -

La struttura del prompt

username@hostname:~/Documenti$ 
username@hostname:~/Documenti$ 
Elemento Significato
username Il tuo nome utente
hostname Il nome del computer
~ Directory corrente (home)
Documenti Cartella corrente
$ Utente normale (se # = root/amministratore)

Comandi fondamentali (devi assolutamente conoscere)

pwd                   # Mostra la directory corrente (Print Working Directory)
ls                    # Elenca file e cartelle
ls -la                # Elenca tutto (anche nascosti) con dettagli
cd /percorso          # Cambia directory (Change Directory)
cd ..                 # Torna alla directory superiore
cd ~                  # Torna alla home (~ è abbreviazione di /home/username)
cd -                  # Torna alla directory precedente
pwd                   # Mostra la directory corrente (Print Working Directory)
ls                    # Elenca file e cartelle
ls -la                # Elenca tutto (anche nascosti) con dettagli
cd /percorso          # Cambia directory (Change Directory)
cd ..                 # Torna alla directory superiore
cd ~                  # Torna alla home (~ è abbreviazione di /home/username)
cd -                  # Torna alla directory precedente

Gestione file e cartelle

touch file.txt        # Crea un file vuoto
mkdir cartella        # Crea una directory (MaKe DIRectory)
mkdir -p a/b/c        # Crea directory annidate (con genitori)
cp sorgente destinazione   # Copia file/directory
cp -r cartella1 cartella2  # Copia ricorsiva (directory)
mv vecchio nuovo       # Sposta o rinomina (MoVe)
rm file.txt           # Rimuove file (ReMove)
rm -r cartella        # Rimuove directory ricorsivamente
rm -rf cartella       # Forza rimozione (attenzione: pericoloso!)
touch file.txt        # Crea un file vuoto
mkdir cartella        # Crea una directory (MaKe DIRectory)
mkdir -p a/b/c        # Crea directory annidate (con genitori)
cp sorgente destinazione   # Copia file/directory
cp -r cartella1 cartella2  # Copia ricorsiva (directory)
mv vecchio nuovo       # Sposta o rinomina (MoVe)
rm file.txt           # Rimuove file (ReMove)
rm -r cartella        # Rimuove directory ricorsivamente
rm -rf cartella       # Forza rimozione (attenzione: pericoloso!)

Visualizzazione file

cat file.txt          # Mostra tutto il file
less file.txt         # Visualizza paginato (q per uscire)
head file.txt         # Mostra prime 10 righe
tail file.txt         # Mostra ultime 10 righe
tail -f log.txt       # Segue il file in tempo reale (log)
cat file.txt          # Mostra tutto il file
less file.txt         # Visualizza paginato (q per uscire)
head file.txt         # Mostra prime 10 righe
tail file.txt         # Mostra ultime 10 righe
tail -f log.txt       # Segue il file in tempo reale (log)

Permessi e proprietà

chmod 755 file        # Cambia permessi (7=rwx, 5=r-x)
chmod +x script.sh    # Rende eseguibile
chown utente:gruppo file  # Cambia proprietario
chmod 755 file        # Cambia permessi (7=rwx, 5=r-x)
chmod +x script.sh    # Rende eseguibile
chown utente:gruppo file  # Cambia proprietario

Comandi di sistema

Informazioni di sistema

whoami                # Chi sei
id                    # Dettagli utente e gruppi
uname -a              # Info kernel Linux
df -h                 # Spazio su disco (leggibile)
free -h               # RAM e swap
top                   # Processi in tempo reale (premi q per uscire)
htop                  # Versione migliorata (installalo!)
whoami                # Chi sei
id                    # Dettagli utente e gruppi
uname -a              # Info kernel Linux
df -h                 # Spazio su disco (leggibile)
free -h               # RAM e swap
top                   # Processi in tempo reale (premi q per uscire)
htop                  # Versione migliorata (installalo!)

Gestione processi

ps aux                # Lista processi
kill PID              # Termina processo per ID
killall nome          # Termina tutti i processi con quel nome
Ctrl + C              # Interrompe il comando in esecuzione
Ctrl + Z              # Mette in pausa (sospende)
jobs                  # Mostra processi sospesi
fg                    # Riporta in primo piano
bg                    # Esegue in background
ps aux                # Lista processi
kill PID              # Termina processo per ID
killall nome          # Termina tutti i processi con quel nome
Ctrl + C              # Interrompe il comando in esecuzione
Ctrl + Z              # Mette in pausa (sospende)
jobs                  # Mostra processi sospesi
fg                    # Riporta in primo piano
bg                    # Esegue in background

Utenti e permessi

sudo comando          # Esegue come superutente (root)
su -                  # Passa a root (switch user)
sudo -i               # Diventa root (interattivo)
passwd                # Cambia la tua password
sudo comando          # Esegue come superutente (root)
su -                  # Passa a root (switch user)
sudo -i               # Diventa root (interattivo)
passwd                # Cambia la tua password

Gestione pacchetti (installare software)

Distribuzione Comando Esempio
Debian/Ubuntu (APT) sudo apt install nome sudo apt install vlc
Fedora/RHEL (DNF) sudo dnf install nome sudo dnf install vlc
openSUSE (Zypper) sudo zypper install nome sudo zypper install vlc
Arch (Pacman) sudo pacman -S nome sudo pacman -S vlc
Snap snap install nome snap install firefox
Flatpak flatpak install flathub nome flatpak install flathub org.videolan.VLC

Comandi APT (Debian/Ubuntu) - i più comuni

sudo apt update               # Aggiorna lista pacchetti
sudo apt upgrade              # Aggiorna tutti i pacchetti
sudo apt install nome         # Installa
sudo apt remove nome          # Rimuove (mantiene configurazioni)
sudo apt purge nome           # Rimuove TUTTO
sudo apt autoremove           # Rimuove dipendenze non più usate
apt search parola             # Cerca pacchetto
apt show nome                 # Mostra info pacchetto
sudo apt update               # Aggiorna lista pacchetti
sudo apt upgrade              # Aggiorna tutti i pacchetti
sudo apt install nome         # Installa
sudo apt remove nome          # Rimuove (mantiene configurazioni)
sudo apt purge nome           # Rimuove TUTTO
sudo apt autoremove           # Rimuove dipendenze non più usate
apt search parola             # Cerca pacchetto
apt show nome                 # Mostra info pacchetto

Redirezione e pipe (la vera potenza della shell)

Redirezione output

comando > file.txt      # Invia output a file (sovrascrive)
comando >> file.txt     # Invia output a file (accoda)
comando 2> errori.txt   # Invia errori (stderr) a file
comando > tutto.txt 2>&1 # Invia sia output che errori
comando > file.txt      # Invia output a file (sovrascrive)
comando >> file.txt     # Invia output a file (accoda)
comando 2> errori.txt   # Invia errori (stderr) a file
comando > tutto.txt 2>&1 # Invia sia output che errori

Pipe (|) - incatena comandi

ls -la | grep ".txt"          # Filtra righe che contengono ".txt"
ps aux | grep firefox         # Cerca processo firefox
cat file.txt | sort | uniq    # Ordina e rimuove duplicati
history | grep apt            # Cerca comandi passati con apt
ls -la | grep ".txt"          # Filtra righe che contengono ".txt"
ps aux | grep firefox         # Cerca processo firefox
cat file.txt | sort | uniq    # Ordina e rimuove duplicati
history | grep apt            # Cerca comandi passati con apt

Esempi pratici

# Contare quante righe ha un file
wc -l file.txt

# Trovare tutti i file .conf modificati oggi
find /etc -name "*.conf" -mtime -1

# Cercare testo dentro file
grep -r "errore" /var/log/

# Monitorare log in tempo reale
tail -f /var/log/syslog
# Contare quante righe ha un file
wc -l file.txt

# Trovare tutti i file .conf modificati oggi
find /etc -name "*.conf" -mtime -1

# Cercare testo dentro file
grep -r "errore" /var/log/

# Monitorare log in tempo reale
tail -f /var/log/syslog

Variabili d'ambiente

echo $PATH           # Mostra dove cerca gli eseguibili
export VAR=valore    # Crea una variabile d'ambiente
echo $VAR            # Mostra valore
echo $HOME           # La tua home
echo $SHELL          # Shell corrente
echo $PATH           # Mostra dove cerca gli eseguibili
export VAR=valore    # Crea una variabile d'ambiente
echo $VAR            # Mostra valore
echo $HOME           # La tua home
echo $SHELL          # Shell corrente

Esempio pratico: Aggiungere una cartella al PATH

export PATH=$PATH:/home/mio/bin
# Ora posso lanciare script nella cartella /home/mio/bin da ovunque
export PATH=$PATH:/home/mio/bin
# Ora posso lanciare script nella cartella /home/mio/bin da ovunque

Comandi utili avanzati

Ricerca

find /home -name "*.jpg"      # Cerca file per nome
grep -r "testo" /percorso     # Cerca testo dentro file
locate nomefile               # Cerca veloce (usa database)
which comando                 # Mostra path dell'eseguibile
whereis comando               # Mostra binario, sorgenti, man page
find /home -name "*.jpg"      # Cerca file per nome
grep -r "testo" /percorso     # Cerca testo dentro file
locate nomefile               # Cerca veloce (usa database)
which comando                 # Mostra path dell'eseguibile
whereis comando               # Mostra binario, sorgenti, man page

Archiviazione e compressione

tar -czf archivio.tar.gz cartella/   # Crea .tar.gz
tar -xzf archivio.tar.gz             # Estrai .tar.gz
tar -xf archivio.tar.xz              # Estrai .tar.xz
zip -r archivio.zip cartella/        # Crea .zip
unzip archivio.zip                   # Estrai .zip
tar -czf archivio.tar.gz cartella/   # Crea .tar.gz
tar -xzf archivio.tar.gz             # Estrai .tar.gz
tar -xf archivio.tar.xz              # Estrai .tar.xz
zip -r archivio.zip cartella/        # Crea .zip
unzip archivio.zip                   # Estrai .zip

Rete

ip a                  # Mostra interfacce di rete e indirizzi IP
ping google.com       # Test connessione
curl ifconfig.me      # Mostra IP pubblico
wget https://file.zip # Scarica file
ssh user@server       # Connessione remota sicura
ip a                  # Mostra interfacce di rete e indirizzi IP
ping google.com       # Test connessione
curl ifconfig.me      # Mostra IP pubblico
wget https://file.zip # Scarica file
ssh user@server       # Connessione remota sicura

Utilità

echo "testo"          # Stampa testo
date                  # Data e ora
cal                   # Calendario
sleep 5               # Attende 5 secondi
clear o Ctrl + L      # Pulisce schermo
exit                  # Chiude terminale
echo "testo"          # Stampa testo
date                  # Data e ora
cal                   # Calendario
sleep 5               # Attende 5 secondi
clear o Ctrl + L      # Pulisce schermo
exit                  # Chiude terminale

Editor di testo da terminale

Editor Difficoltà Caratteristiche
nano Facile Semplice, intuitivo (per principianti)
vim Difficile Potente, ovunque presente
neovim Difficile Versione moderna di vim
emacs Molto difficile Estremamente estensibile

Usare nano (il più semplice)

nano file.txt
# Ctrl + O = salva
# Ctrl + X = esci
# Ctrl + W = cerca
# Alt + U = annulla
nano file.txt
# Ctrl + O = salva
# Ctrl + X = esci
# Ctrl + W = cerca
# Alt + U = annulla

Scorciatoie da terminale (funzionano quasi ovunque)

Scorciatoia Effetto
Ctrl + A Vai all'inizio della riga
Ctrl + E Vai alla fine della riga
Ctrl + U Cancella dall'inizio al cursore
Ctrl + K Cancella dal cursore alla fine
Ctrl + W Cancella parola prima del cursore
Ctrl + R Cerca nei comandi precedenti
Ctrl + L Pulisci schermo (come clear)
Tab Autocompletamento
/ Naviga cronologia comandi
!! Ripeti ultimo comando
!apt Ripeti ultimo comando che inizia con "apt"

Cronologia comandi

history               # Mostra tutti i comandi recenti
!!                    # Esegue l'ultimo comando
!123                  # Esegue comando numero 123
!cat                  # Esegue ultimo comando iniziante per "cat"
Ctrl + R              # Cerca interattivamente nella cronologia
history               # Mostra tutti i comandi recenti
!!                    # Esegue l'ultimo comando
!123                  # Esegue comando numero 123
!cat                  # Esegue ultimo comando iniziante per "cat"
Ctrl + R              # Cerca interattivamente nella cronologia

Scripting basilare (automatizzare compiti)

Crea un file mio_script.sh:

#!/bin/bash
# Questo è un commento

echo "Ciao, $USER!"
data=$(date)
echo "Oggi è $data"

if [ -f "/tmp/test.txt" ]; then
    echo "Il file esiste"
else
    echo "File non trovato"
fi

for i in {1..5}; do
    echo "Numero $i"
done
#!/bin/bash
# Questo è un commento

echo "Ciao, $USER!"
data=$(date)
echo "Oggi è $data"

if [ -f "/tmp/test.txt" ]; then
    echo "Il file esiste"
else
    echo "File non trovato"
fi

for i in {1..5}; do
    echo "Numero $i"
done

Esegui:

chmod +x mio_script.sh
./mio_script.sh
chmod +x mio_script.sh
./mio_script.sh

Personalizzazione (rendi il terminale tuo)

Modificare prompt (PS1)

# Semplice
export PS1="\u@\h:\w\$ "

# Con colori
export PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "

# Aggiungi al file ~/.bashrc per renderlo permanente
echo 'export PS1="\u@\h:\w\$ "' >> ~/.bashrc
# Semplice
export PS1="\u@\h:\w\$ "

# Con colori
export PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "

# Aggiungi al file ~/.bashrc per renderlo permanente
echo 'export PS1="\u@\h:\w\$ "' >> ~/.bashrc

Alias (scorciatoie personali)

alias ll='ls -la'
alias update='sudo apt update && sudo apt upgrade'
alias gs='git status'

# Permanenti: aggiungi a ~/.bashrc
echo "alias ll='ls -la'" >> ~/.bashrc
source ~/.bashrc   # Ricarica configurazione
alias ll='ls -la'
alias update='sudo apt update && sudo apt upgrade'
alias gs='git status'

# Permanenti: aggiungi a ~/.bashrc
echo "alias ll='ls -la'" >> ~/.bashrc
source ~/.bashrc   # Ricarica configurazione

Esercizi pratici per imparare

Livello 1 (principiante)

# 1. Crea una struttura di cartelle
mkdir -p progetti/{2024,2025}/documenti

# 2. Crea 5 file vuoti
touch file{1..5}.txt

# 3. Sposta i file .txt in documenti/
mv *.txt progetti/2024/documenti/

# 4. Conta quanti file ci sono
ls -l | wc -l
# 1. Crea una struttura di cartelle
mkdir -p progetti/{2024,2025}/documenti

# 2. Crea 5 file vuoti
touch file{1..5}.txt

# 3. Sposta i file .txt in documenti/
mv *.txt progetti/2024/documenti/

# 4. Conta quanti file ci sono
ls -l | wc -l

Livello 2 (intermedio)

# 5. Trova tutti i file modificati oggi
find ~ -type f -mtime 0

# 6. Cerca un processo e uccidilo in un colpo
kill $(ps aux | grep "nome_processo" | awk '{print $2}')

# 7. Monitora log in tempo reale filtrando errori
tail -f /var/log/syslog | grep -i error

# 8. Backup automatico
tar -czf backup_$(date +%Y%m%d).tar.gz ~/Documenti/
# 5. Trova tutti i file modificati oggi
find ~ -type f -mtime 0

# 6. Cerca un processo e uccidilo in un colpo
kill $(ps aux | grep "nome_processo" | awk '{print $2}')

# 7. Monitora log in tempo reale filtrando errori
tail -f /var/log/syslog | grep -i error

# 8. Backup automatico
tar -czf backup_$(date +%Y%m%d).tar.gz ~/Documenti/

Risorse per imparare

Risorsa Tipo Link/Comando
man Manuale integrato man ls
tldr Esempi pratici sudo apt install tldrtldr ls
cheat Foglietto interattivo sudo snap install cheat
explainshell Spiega comandi online explainshell.com

Errori comuni e come risolverli

Errore Causa Soluzione
command not found Comando non installato o sbagliato sudo apt install comando o controlla spelling
permission denied Permessi insufficienti Usa sudo o chmod +x
No such file or directory Percorso sbagliato Controlla con ls o usa tab completamento
cannot create: Read-only file system Disco montato in sola lettura Rimonta come sudo mount -o remount,rw /

In sintesi: il terminale non è difficile

Prima settimana:
- Impara cd, ls, pwd, mkdir, rm
- Usa Ctrl + C, Ctrl + L, ↑/↓

Primo mese:
- Impara grep, find, pipe (|)
- Usa apt installare software
- Modifica file con nano

Dopo 3 mesi:
- Script semplici
- Alias personalizzati
- Usi il terminale più della GUI
Prima settimana:
- Impara cd, ls, pwd, mkdir, rm
- Usa Ctrl + C, Ctrl + L, ↑/↓

Primo mese:
- Impara grep, find, pipe (|)
- Usa apt installare software
- Modifica file con nano

Dopo 3 mesi:
- Script semplici
- Alias personalizzati
- Usi il terminale più della GUI

Consiglio finale: Non cercare di imparare tutto in una volta. Inizia con 5-10 comandi e usali ogni giorno. Quando ti senti a tuo agio, aggiungine altri.

English version

Linux Terminal

What is the terminal?

The terminal is a text interface that allows you to communicate directly with the operating system by typing commands. Unlike a graphical interface (mouse, windows, icons), here you write precise instructions.

Correct Terminology

Term Meaning
Terminal The window program that displays the prompt (e.g., GNOME Terminal, Konsole, xterm)
Shell The command interpreter (e.g., bash, zsh, fish)
Console Historically the physical terminal, now synonymous with terminal
Prompt The text waiting for a command, e.g., $ (normal user) or # (root)

Most Common Shells

Shell Features Default to
bash Standard, ubiquitous, powerful scripting Ubuntu, Debian, RHEL, Fedora
zsh Advanced autocompletion, plugins, themes macOS, Kali Linux
fish Interactive tooltips, easy setup - (installable)
dash Lightweight, fast, POSIX-compliant Debian/Ubuntu for system scripting

How to open the terminal

| Distribution | Shortcut | Alternative method |
|--------------|- ... Menu → Terminal |
| Fedora | Ctrl + Alt + T | Tasks → Terminal |
| Pop!_OS | Super + T | Dock → Terminal |
| Any | Ctrl + Alt + F3 (pure TTY, no GUI) | - |


The prompt structure

username@hostname:~/Documents$
username@hostname:~/Documents$
Element Meaning
username Your username
hostname The name of your computer
~ Current directory (home)
Documents Current folder
$ Normal user (if # = root/administrator)

Essential Commands (Must Know)

File System Navigation

pwd # Print the current directory (Print Working Directory)
ls # List files and folders
ls -la # List everything (even hidden ones) with details
cd /path # Change Directory
cd .. # Return to the parent directory
cd ~ # Return to the home directory (~ is short for /home/username)
cd - # Return to the previous directory
pwd # Print the current directory (Print Working Directory)
ls # List files and folders
ls -la # List everything (even hidden ones) with details
cd /path # Change Directory
cd .. # Return to the parent directory
cd ~ # Return to the home directory (~ is short for /home/username)
cd - # Return to the previous directory

File and Folder Management

touch file.txt # Create an empty file
mkdir folder # Create a directory (MaKe DIRectory)
mkdir -p a/b/c # Create nested directories (with parents)
cp source destination # Copy file/directory
cp -r folder1 folder2 # Recursive copy (directory)
mv old new # Move or rename (MoVe)
rm file.txt # Remove files (ReMove)
rm -r folder # Removes directories recursively
rm -rf folder # Force removal (warning: dangerous!)
touch file.txt # Create an empty file
mkdir folder # Create a directory (MaKe DIRectory)
mkdir -p a/b/c # Create nested directories (with parents)
cp source destination # Copy file/directory
cp -r folder1 folder2 # Recursive copy (directory)
mv old new # Move or rename (MoVe)
rm file.txt # Remove files (ReMove)
rm -r folder # Removes directories recursively
rm -rf folder # Force removal (warning: dangerous!)

File View

cat file.txt # Shows the entire file
less file.txt # View paginated (q to exit)
head file.txt # Shows the first 10 lines
tail file.txt # Shows the last 10 lines
tail -f log.txt # Tracks the file in real time (log)
cat file.txt # Shows the entire file
less file.txt # View paginated (q to exit)
head file.txt # Shows the first 10 lines
tail file.txt # Shows the last 10 lines
tail -f log.txt # Tracks the file in real time (log)

Permissions and Ownership

chmod 755 file # Changes permissions (7=rwx, 5=r-x)
chmod +x script.sh # Makes it executable
chown user:group file # Changes ownership
chmod 755 file # Changes permissions (7=rwx, 5=r-x)
chmod +x script.sh # Makes it executable
chown user:group file # Changes ownership

System Commands

System Information

whoami # Who you are
id # User and group details
uname -a # Kernel info Linux
df -h # Disk space (readable)
free -h # RAM and swap
top # Real-time processes (press q to exit)
htop # Improved version (install it!)
whoami # Who you are
id # User and group details
uname -a # Kernel info Linux
df -h # Disk space (readable)
free -h # RAM and swap
top # Real-time processes (press q to exit)
htop # Improved version (install it!)

Process Manager

ps aux # Process List
kill PID # Kill process by ID
killall name # Kill all processes with that name
Ctrl + C # Stops the running command
Ctrl + Z # Pauses (suspends)
jobs # Shows suspended processes
fg # Brings to the foreground
bg # Runs in the background
ps aux # Process List
kill PID # Kill process by ID
killall name # Kill all processes with that name
Ctrl + C # Stops the running command
Ctrl + Z # Pauses (suspends)
jobs # Shows suspended processes
fg # Brings to the foreground
bg # Runs in the background

Users and Permissions

sudo command # Run as superuser (root)
su - # Switch to root (switch user)
sudo -i # Become root (interactive)
passwd # Change your password
sudo command # Run as superuser (root)
su - # Switch to root (switch user)
sudo -i # Become root (interactive)
passwd # Change your password

Package Management (Installing Software)

Distribution Command Example
Debian/Ubuntu (APT) sudo apt install name sudo apt install vlc
Fedora/RHEL (DNF) sudo dnf install name sudo dnf install vlc
openSUSE (Zypper) sudo zypper install name sudo zypper install vlc
Arch (Pacman) sudo pacman -S name sudo pacman -S vlc
Snap snap install name snap install firefox
Flatpak flatpak install flathub name flatpak install flathub org.videolan.VLC

APT Commands (Debian/Ubuntu) - The Most Common

sudo apt update # Update package list
sudo apt upgrade # Update all packages
sudo apt install name # Install
sudo apt remove name # Remove (keep configurations)
sudo apt purge name # Remove ALL
sudo apt autoremove # Remove unused dependencies
apt search word # Search for a package
apt show name # Show package info
sudo apt update # Update package list
sudo apt upgrade # Update all packages
sudo apt install name # Install
sudo apt remove name # Remove (keep configurations)
sudo apt purge name # Remove ALL
sudo apt autoremove # Remove unused dependencies
apt search word # Search for a package
apt show name # Show package info

Redirection and Pipes (The Real Power of the Shell)

Output Redirection

command > file.txt # Send output to file (overwrite)
command >> file.txt # Send output to file (append)
command 2> errors.txt # Send errors (stderr) to file
command > all.txt 2>&1 # Send both output and errors
command > file.txt # Send output to file (overwrite)
command >> file.txt # Send output to file (append)
command 2> errors.txt # Send errors (stderr) to file
command > all.txt 2>&1 # Send both output and errors

Pipes (|) - chain commands

ls -la | grep ".txt" # Filter lines containing ".txt"
ps aux | grep firefox # Search for firefox process
cat file.txt | sort | uniq # Sort and remove duplicates
history | grep apt # Find past commands with apt
ls -la | grep ".txt" # Filter lines containing ".txt"
ps aux | grep firefox # Search for firefox process
cat file.txt | sort | uniq # Sort and remove duplicates
history | grep apt # Find past commands with apt

Practical Examples

# Count how many lines a file has
wc -l file.txt

# Find all .conf files modified today
find /etc -name "*.conf" -mtime -1

# Search for text within files
grep -r "error" /var/log/

# Monitor logs in real time
tail -f /var/log/syslog
# Count how many lines a file has
wc -l file.txt

# Find all .conf files modified today
find /etc -name "*.conf" -mtime -1

# Search for text within files
grep -r "error" /var/log/

# Monitor logs in real time
tail -f /var/log/syslog

Environment Variables

echo $PATH # Show where to search for executables
export VAR=value # Create an environment variable
echo $VAR # Show value
echo $HOME # Your home
echo $SHELL # Current shell
echo $PATH # Show where to search for executables
export VAR=value # Create an environment variable
echo $VAR # Show value
echo $HOME # Your home
echo $SHELL # Current shell

Practical Example: Add a folder to the PATH

export PATH=$PATH:/home/my/bin
# Now I can run scripts in the /home/my/bin folder from anywhere
export PATH=$PATH:/home/my/bin
# Now I can run scripts in the /home/my/bin folder from anywhere

Advanced Useful Commands

find /home -name "*.jpg" # Search for files by name
grep -r "text" /path # Search for text within files
locate filename # Quick search (use database)
which command # Show executable path
whereis command # Show binary, source, man page
find /home -name "*.jpg" # Search for files by name
grep -r "text" /path # Search for text within files
locate filename # Quick search (use database)
which command # Show executable path
whereis command # Show binary, source, man page

Archiving and Compression

tar -czf archive.tar.gz folder/ # Create .tar.gz
tar -xzf archive.tar.gz # Extract .tar.gz
tar -xf archive.tar.xz # Extract .tar.xz
zip -r archive.zip folder/ # Create .zip
unzip archive.zip # Extract .zip
tar -czf archive.tar.gz folder/ # Create .tar.gz
tar -xzf archive.tar.gz # Extract .tar.gz
tar -xf archive.tar.xz # Extract .tar.xz
zip -r archive.zip folder/ # Create .zip
unzip archive.zip # Extract .zip

Network

ip a # Show network interfaces and IP addresses
ping google.com # Test connection
curl ifconfig.me # Show public IP
wget https://file.zip # Download file
ssh user@server # Secure remote connection
ip a # Show network interfaces and IP addresses
ping google.com # Test connection
curl ifconfig.me # Show public IP
wget https://file.zip # Download file
ssh user@server # Secure remote connection

Utilities

echo "text" # Print text
date # Date and time
cal # Calendar
sleep 5 # Wait 5 seconds
clear or Ctrl + L # Clear screen
exit # Close terminal
echo "text" # Print text
date # Date and time
cal # Calendar
sleep 5 # Wait 5 seconds
clear or Ctrl + L # Clear screen
exit # Close terminal

Terminal Text Editor

| Editor | Difficulty | Features |
|--------|- ... neovim | Difficult | Modern version of vim |
| emacs | Very Difficult | Extremely Extensible |

Using nano (the simplest)

nano file.txt
# Ctrl + O = save
# Ctrl + X = exit
# Ctrl + W = search
# Alt + U = cancel
nano file.txt
# Ctrl + O = save
# Ctrl + X = exit
# Ctrl + W = search
# Alt + U = cancel

Terminal Shortcuts (work almost everywhere)

Shortcut Effect
Ctrl + A Go to beginning of line
Ctrl + E Go to end of line
Ctrl + U Delete from beginning to cursor
Ctrl + K Delete from cursor to end
Ctrl + W Delete word before cursor
Ctrl + R Search previous commands
Ctrl + L Clear screen (like clear)
Tab Autocomplete
/ Navigate command history
!! Repeat last command
!apt Repeat last command starting with "apt"

Command history

history # Show all recent commands
!! # Executes the last command
!123 # Executes command number 123
!cat # Executes the last command starting with "cat"
Ctrl + R # Interactively search the history
history # Show all recent commands
!! # Executes the last command
!123 # Executes command number 123
!cat # Executes the last command starting with "cat"
Ctrl + R # Interactively search the history

Basic Scripting (Automating Tasks)

Create a file my_script.sh:

#!/bin/bash
# This is a comment

echo "Hello, $USER!"
data=$(date)
echo "Today is $date"

if [ -f "/tmp/test.txt" ]; then
echo "File exists"
else
echo "File not found"
fi

for i in {1..5}; do
echo "Number $i"
done
#!/bin/bash
# This is a comment

echo "Hello, $USER!"
data=$(date)
echo "Today is $date"

if [ -f "/tmp/test.txt" ]; then
echo "File exists"
else
echo "File not found"
fi

for i in {1..5}; do
echo "Number $i"
done

Run:

chmod +x my_script.sh
./my_script.sh
chmod +x my_script.sh
./my_script.sh

Customization (make the terminal your own)

Modifying prompt (PS1)

# Simple and
export PS1="\u@\h:\w\$ "

# With colors
export PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "

# Add to ~/.bashrc file to make it permanent
echo 'export PS1="\u@\h:\w\$ "' >> ~/.bashrc
# Simple and
export PS1="\u@\h:\w\$ "

# With colors
export PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "

# Add to ~/.bashrc file to make it permanent
echo 'export PS1="\u@\h:\w\$ "' >> ~/.bashrc

Aliases (personal shortcuts)

alias ll='ls -la'
alias update='sudo apt update && sudo apt upgrade'
alias gs='git status'

# Permanent: Add to ~/.bashrc
echo "alias ll='ls -la'" >> ~/.bashrc
source ~/.bashrc # Reload configuration
alias ll='ls -la'
alias update='sudo apt update && sudo apt upgrade'
alias gs='git status'

# Permanent: Add to ~/.bashrc
echo "alias ll='ls -la'" >> ~/.bashrc
source ~/.bashrc # Reload configuration

Practical exercises to learn

Level 1 (beginner)

# 1. Create a folder structure
mkdir -p projects/{2024,2025}/documents

# 2. Create 5 empty files
touch file{1..5}.txt

# 3. Move the .txt files to documents/
mv *.txt projects/2024/documents/

# 4. Count how many files there are
ls -l | wc -l
# 1. Create a folder structure
mkdir -p projects/{2024,2025}/documents

# 2. Create 5 empty files
touch file{1..5}.txt

# 3. Move the .txt files to documents/
mv *.txt projects/2024/documents/

# 4. Count how many files there are
ls -l | wc -l

Level 2 (Intermediate)

# 5. Find all files modified today
find ~ -type f -mtime 0

# 6. Find a process and kill it in one hit
kill $(ps aux | grep "process_name" | awk '{print $2}')

# 7. Monitor logs in real time, filtering errors
tail -f /var/log/syslog | grep -i error

# 8. Automatic backup
tar -czf backup_$(date +%Y%m%d).tar.gz ~/Documents/
# 5. Find all files modified today
find ~ -type f -mtime 0

# 6. Find a process and kill it in one hit
kill $(ps aux | grep "process_name" | awk '{print $2}')

# 7. Monitor logs in real time, filtering errors
tail -f /var/log/syslog | grep -i error

# 8. Automatic backup
tar -czf backup_$(date +%Y%m%d).tar.gz ~/Documents/

Learning Resources

| Resource | Type | Link/Command |
|--------|-------------|
| man | Integrated Manual | man ls |
| tldr | Practical Examples | sudo apt install tldrtldr ls |
| cheat | Interactive Cheat Sheet | sudo snap install cheat |
| explainshell | Explain commands online | explainshell.com |


Common Errors and How to Fix Them

Error Cause Solution
command not found Command not installed or incorrect sudo apt install command or check spelling
permission denied Insufficient permissions Use sudo or chmod +x
No such file or directory Incorrect path Check with ls or use tab completion
cannot create: Read-only file system Mount disk read-only Remount as sudo mount -o remount,rw /

Bottom line: The terminal isn't difficult

First week:
- Learn cd, ls, pwd, mkdir, rm
- Use Ctrl + C, Ctrl + L, ↑/↓

First month:
- Learn grep, find, pipe (|)
- Use apt to install software
- Edit files with nano

After 3 months:
- Simple scripts
- Custom aliases
- Use the terminal more than the GUI
First week:
- Learn cd, ls, pwd, mkdir, rm
- Use Ctrl + C, Ctrl + L, ↑/↓

First month:
- Learn grep, find, pipe (|)
- Use apt to install software
- Edit files with nano

After 3 months:
- Simple scripts
- Custom aliases
- Use the terminal more than the GUI

Final tip: Don't try to learn everything at once. Start with 5-10 commands and use them every day. As you feel comfortable, add more.


Puoi seguire anche il mio canale YouTube https://www.youtube.com/channel/UCoOgys_fRjBrHmx2psNALow/ con tanti video interessanti


I consigli che offriamo sono di natura generale. Non sono consigli legali o professionali. Quello che può funzionare per una persona potrebbe non essere adatto a un’altra, e dipende da molte variabili.

Commenti