RousselTMLEARNING

Article · Linux administration: from discovery to expertise

The Bash shell and files

1. Moving around #

Paths and navigation.

Absolute and relative paths #

Absolute and relative paths
A relative path depends on the current directory; an absolute path never does.

An absolute path starts from the root (/etc/nginx/nginx.conf), a relative path starts from the current directory (../logs). ~ means the home directory, . the current directory, .. the parent.

pwd                  # où suis-je ?
cd /var/log ; cd -   # aller puis revenir au répertoire précédent
ls -lah              # liste détaillée, fichiers cachés, tailles lisibles
ls -lt | head        # fichiers les plus récents
tree -L 2 /etc/nginx # arborescence sur 2 niveaux

The prompt and history #

history | grep systemctl   # retrouver une commande
!!                         # relancer la dernière commande (sudo !! si oubli de sudo)
Ctrl+R                     # recherche incrémentale dans l'historique
Ctrl+A / Ctrl+E            # début / fin de ligne
Tab                        # complétion des commandes et chemins

2. Handling files #

Create, copy, move, delete.

Basic commands #

mkdir -p projet/{src,docs,tests}   # créer une arborescence
touch notes.txt                    # créer un fichier vide
cp -a /etc/nginx /etc/nginx.bak    # copier en préservant droits et dates
mv rapport.txt archives/           # déplacer ou renommer
rm -i fichier ; rm -r dossier      # supprimer (sans corbeille !)
ln -s /srv/app/current app         # lien symbolique
stat fichier ; file fichier        # métadonnées, type réel
Common mistake: rm -rf asks for no confirmation and there is no trash. Check the variable before rm -rf "$DIR"/*: if it is empty, the command targets the root.

Wildcards (globbing) #

PatternMatches
*.logall files ending in .log
app?.confapp1.conf, appA.conf
[0-9]*starts with a digit
{a,b}.txta.txt and b.txt (expansion, even if they do not exist)

It is the shell that expands wildcards before running the command: echo *.log shows what the command will receive.

Reading a file #

cat fichier            # tout afficher
less /var/log/syslog   # paginer (/ pour chercher, q pour quitter)
head -n 20 ; tail -n 50
tail -f /var/log/nginx/error.log   # suivre en temps réel
wc -l fichier          # nombre de lignes

3. Redirections and pipes #

Assembling small commands.

Standard streams #

Standard streams of a command
Separating stdout and stderr lets you keep the results and discard or log the errors.
StreamNumberRedirection
Standard input (stdin)0< file
Standard output (stdout)1> file (overwrite), >> file (append)
Standard error (stderr)22> errors.log, 2>&1 (to stdout)
find / -name '*.conf' 2>/dev/null     # masquer les erreurs de permission
./backup.sh > backup.log 2>&1         # tout dans un fichier
./backup.sh 2>&1 | tee backup.log     # afficher et enregistrer
sudo tee /etc/motd <<'EOF'            # écrire un fichier root (heredoc)
Serveur de production : soyez prudent.
EOF

The pipe #

Command pipeline
The Unix philosophy: simple tools that do one thing and combine.
Analyzing an access log
In two lines, you find the URL responsible for the 500 errors.
Good to know: sudo echo x > /etc/file fails: the redirection is done by your shell, without root rights. Use echo x | sudo tee /etc/file.

4. Searching and transforming text #

find, grep, sed, awk and friends.

Finding files #

find /var/log -name '*.log' -mtime -1          # modifiés depuis 24 h
find / -xdev -type f -size +500M 2>/dev/null   # gros fichiers sur la partition racine
find /srv -user www-data -perm -o+w            # fichiers modifiables par tous
find /tmp -type f -mtime +7 -delete            # nettoyer
locate nginx.conf                              # recherche rapide par index (updatedb)

Searching inside files #

grep -i error /var/log/syslog
grep -rn 'listen' /etc/nginx/          # récursif avec numéros de ligne
grep -v '^#' sshd_config | grep -v '^$' # configuration sans commentaires ni lignes vides
grep -E 'error|fail' -c app.log        # expression étendue, compter
zgrep 'Out of memory' /var/log/syslog*.gz

Transforming #

cut -d: -f1,7 /etc/passwd                  # colonnes 1 et 7, séparateur :
sort -t: -k3 -n /etc/passwd                # trier numériquement sur la 3e colonne
sort | uniq -c | sort -rn                  # compter les occurrences
tr 'a-z' 'A-Z' < fichier                   # remplacer des caractères
sed -i.bak 's/^#Port 22/Port 2222/' /etc/ssh/sshd_config   # remplacer en place, avec sauvegarde
sed -n '10,20p' fichier                    # afficher les lignes 10 à 20
awk -F: '$3 >= 1000 {print $1}' /etc/passwd # utilisateurs « humains »
awk '{s += $10} END {print s/1024/1024 " Mo"}' access.log   # somme d'une colonne
diff -u ancien.conf nouveau.conf           # comparer deux fichiers
Good practice: Before running sed -i on a configuration file, test without -i to see the result, and keep a copy (-i.bak).

5. Archives and editing #

tar, compression and vim.

Archiving and compressing #

tar -czf etc-$(date +%F).tar.gz /etc     # créer une archive gzip
tar -tzf etc-2026-10-26.tar.gz | head    # lister le contenu
tar -xzf archive.tar.gz -C /tmp/restore  # extraire ailleurs
tar -cJf logs.tar.xz /var/log/app        # compression xz (plus forte)
zip -r site.zip /srv/www ; unzip site.zip
gzip -9 gros.log ; zcat gros.log.gz | less

Surviving in vim #

vim modes
Lost in vim? Escape, then :q! to quit without saving.
KeyAction
iswitch to insert mode
Escapeback to normal mode
:w / :q / :wq / :q!save / quit / both / quit without saving
/pattern, nsearch, next occurrence
dd, yy, pcut, copy, paste a line
uundo
:%s/old/new/greplace everywhere

nano is simpler for beginners (shortcuts shown at the bottom). Choose your default editor with sudo update-alternatives --config editor or the EDITOR variable.

📄 The Bash shell and files: navigation, redirections, pipes and text processing →

My progress

  • ⏱ Estimated time : ≈ 11 min

Sign in to track your progress and take notes. Sign in

💬 Questions about this lesson

No questions yet: be the first to ask for help or share your configuration.

Ask a question about this lesson →

Recommended Articles

Linux vs Unix: the complete guide to commands and distributions

Understand the differences between Linux and Unix, explore distributions (server, desktop, lightw...

Bash scripts for administrators: writing robust scripts

Automate Linux administration with Bash: variables and quoting, conditions, loops, functions, exi...

Backup, monitoring and troubleshooting of a Linux server

Operate a Linux server day to day: 3-2-1 backup strategy with rsync, tar, LVM snapshots and resti...

Users, groups, sudo and permissions on Linux

Manage Linux accounts (useradd, usermod, passwd, chage), groups, sudo and visudo, rwx and octal p...

Storage on Linux: disks, partitions, file systems and LVM

Administer Linux storage: lsblk and blkid, GPT partitioning, ext4 and XFS, mounting and /etc/fsta...

Networking on Linux: configuration, diagnosis, firewall and SSH

Configure and troubleshoot Linux networking: ip, ss, netplan and NetworkManager, DNS, layered dia...

Linux server security and hardening

Harden a Linux server: least privilege, updates, secure SSH, firewall, fail2ban, SELinux and AppA...

Linux administration best practices

Checklist for administering Linux servers: accounts and sudo, SSH, updates, systemd services, sto...

Packages, systemd services, logs and scheduled tasks

Install and update software with apt and dnf, manage services with systemctl, write a systemd uni...

Support us

♥ SUPPORT US

Support RousselTM Learning

Courses, articles, labs and certificates stay free with no intrusive ads. A voluntary contribution, of any amount you choose, pays for hosting, lab environments and new content.

Contribute with PayPal Any amount · card or PayPal accountLearn more
QR code PayPal
Or scan this QR code with your phone

Thank you, every contribution counts!