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 system architecture: kernel, boot and directory tree

Understand how a Linux server works: kernel and user space, the UEFI, GRUB, initramfs and systemd...

Processes, memory and performance: monitoring and troubleshooting a Linux server

Understand and control Linux processes (ps, top, signals, nice, jobs), interpret load, memory and...

Ansible: ad-hoc commands

Run immediate actions on a fleet of servers with ansible: the ping, command, shell, copy, apt, se...

Ansible: generating dynamic files with Jinja2 and facts

Create dynamic configuration files: Jinja2 templates, variables, facts, filters, loops, condition...

Understanding Google Cloud: regions, projects, hierarchy, tools and pricing

Google Cloud basics: regions and zones, the organization, folders and projects hierarchy, APIs to...

Understanding Azure: regions, resource hierarchy, tools and pricing

Microsoft Azure basics: geographies, regions, region pairs and availability zones, the hierarchy ...

PowerShell for Windows administrators

Master PowerShell to administer Windows: cmdlets and help, object pipeline, filters and formats, ...

Windows networking: IP, DNS, DHCP, firewall and remote access

Configure and troubleshoot Windows networking with PowerShell, deploy a DHCP server, master Windo...

Users, groups, NTFS permissions and SMB shares

Manage local accounts and groups, understand UAC, apply NTFS permissions with inheritance, create...

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!