Skip to main content

Redirections and pipes


Table of contents

  1. stdin, stdout, stderr
  2. Redirections (>, >>, <, 2>)
  3. Pipes: |
  4. tee and xargs
  5. Advanced combinations
  6. Hands-on exercises


1 - stdin, stdout, stderr

The three standard streams

Every Linux process has three data streams:

StreamDescriptorUsage
stdin0Standard input (keyboard)
stdout1Standard output (results)
stderr2Standard error (error messages)

Example

# Cette commande utilise les 3 flux
ls /home /inexistant

# stdout : liste de /home (succès)
# stderr : message d'erreur pour /inexistant

Why separate stdout and stderr?

This lets you:

  • Redirect the results to a file
  • Keep errors on screen
  • Or the reverse
  • Or redirect both separately

🔝 Back to table of contents



2 - Redirections: >, >>, <, 2>

Redirect stdout

# Écrire dans un fichier (écrase)
echo "Hello" > fichier.txt

# Ajouter à un fichier (append)
echo "World" >> fichier.txt

# Résultat dans fichier.txt :
# Hello
# World

# Lister vers un fichier
ls -la > liste.txt

Redirect stderr

# Rediriger les erreurs
ls /inexistant 2> erreurs.txt

# Rediriger erreurs et ajouter
commande 2>> erreurs.log

Redirect stdout AND stderr

# Méthode 1 : Séparément
commande > output.txt 2> errors.txt

# Méthode 2 : Tout dans le même fichier
commande > all.txt 2>&1

# Méthode 3 : Syntaxe moderne (bash 4+)
commande &> all.txt

# Méthode 4 : Ajouter les deux
commande >> all.txt 2>&1

Redirect stdin

# Lire depuis un fichier
wc -l < fichier.txt

# Équivalent (mais moins élégant)
cat fichier.txt | wc -l

/dev/null - The black hole

/dev/null absorbs everything you send to it.

# Ignorer la sortie
commande > /dev/null

# Ignorer les erreurs
commande 2> /dev/null

# Ignorer tout
commande > /dev/null 2>&1
# ou
commande &> /dev/null

Summary table

SyntaxEffect
>Redirect stdout (overwrites)
>>Redirect stdout (appends)
2>Redirect stderr (overwrites)
2>>Redirect stderr (appends)
&>Redirect stdout + stderr
<Redirect stdin
2>&1Send stderr to stdout

🔝 Back to table of contents



3 - Pipes: |

Concept

The pipe | connects the output of one command to the input of the next.

Basic examples

# Compter les fichiers
ls | wc -l

# Filtrer une liste
cat /etc/passwd | grep root

# Trier et filtrer
ls -la | sort -k5 -n | head -10

Chain several commands

# Pipeline complexe
cat access.log | grep "404" | cut -d' ' -f1 | sort | uniq -c | sort -rn | head -10

Breakdown:

  1. cat access.log: Read the file
  2. grep "404": Filter the 404 errors
  3. cut -d' ' -f1: Extract the first field (IP)
  4. sort: Sort
  5. uniq -c: Count unique occurrences
  6. sort -rn: Sort by descending count
  7. head -10: Keep the top 10

Practical examples

# Top 5 processus par mémoire
ps aux | sort -k4 -rn | head -5

# Utilisateurs connectés uniques
who | cut -d' ' -f1 | sort -u

# Fichiers les plus gros
du -sh * | sort -rh | head -10

# Compter les lignes contenant "error"
grep -i error /var/log/syslog | wc -l

# IPs uniques dans un log
cat access.log | awk '{print $1}' | sort -u
tip

Pipes only pass stdout. Errors (stderr) do not go through the pipe by default.

🔝 Back to table of contents



4 - tee and xargs

tee - Split the output

tee sends the output to a file AND displays it on the screen.

# Voir ET sauvegarder
ls -la | tee liste.txt

# Ajouter au fichier
ls -la | tee -a liste.txt

# Écrire dans plusieurs fichiers
ls | tee fichier1.txt fichier2.txt fichier3.txt

# Pipeline avec tee intermédiaire
cat log.txt | grep error | tee errors.txt | wc -l

xargs - Build commands

xargs turns stdin into arguments for a command.

# Supprimer des fichiers listés
find . -name "*.tmp" | xargs rm

# Avec confirmation
find . -name "*.tmp" | xargs -p rm

# Un par un
find . -name "*.tmp" | xargs -I {} rm -v {}

# Limiter le nombre d'arguments
echo "a b c d e" | xargs -n 2 echo
# a b
# c d
# e

Practical examples with xargs

# Compresser plusieurs fichiers
find . -name "*.log" | xargs gzip

# Chercher dans plusieurs fichiers
find . -name "*.py" | xargs grep "import"

# Copier avec structure
find . -name "*.jpg" | xargs -I {} cp {} /backup/

# Exécuter en parallèle
cat urls.txt | xargs -P 4 -I {} curl -O {}

Useful xargs options

OptionEffect
-I {}Placeholder for the argument
-n NN arguments per command
-P NN commands in parallel
-pAsk for confirmation
-0Null separator (with find -print0)

🔝 Back to table of contents



5 - Advanced combinations

Process substitution

# Comparer deux sorties de commande
diff <(ls dir1) <(ls dir2)

# Utiliser la sortie comme fichier
grep -f <(echo -e "pattern1\npattern2") fichier.txt

Here documents

# Entrée multiligne
cat << EOF
Ligne 1
Ligne 2
Ligne 3
EOF

# Avec variable
cat << EOF > config.txt
DATABASE_URL=$DATABASE_URL
APP_NAME=MonApp
EOF

Here strings

# Entrée d'une ligne
grep "pattern" <<< "texte à chercher"

# Avec variable
wc -w <<< "$MESSAGE"

Commands in a subshell

# Exécuter dans un sous-shell
(cd /tmp && ls)
# Le répertoire courant n'a pas changé

# Capturer la sortie
FILES=$(ls *.txt)
echo "Fichiers trouvés : $FILES"

One-liner script examples

# Backup avec date
tar czf backup-$(date +%Y%m%d).tar.gz /data

# Trouver et supprimer les fichiers vides
find . -type f -empty -delete

# Remplacer dans plusieurs fichiers
grep -rl "ancien" . | xargs sed -i 's/ancien/nouveau/g'

# Surveillance de log en temps réel avec filtre
tail -f /var/log/syslog | grep --line-buffered "error"

# Top 10 des commandes les plus utilisées
history | awk '{print $2}' | sort | uniq -c | sort -rn | head -10

🔝 Back to table of contents



6 - Hands-on exercises

Exercise 1: Redirections

# 1. Créez un fichier avec la liste de /etc
ls /etc > etc_list.txt

# 2. Ajoutez la liste de /var
ls /var >> etc_list.txt

# 3. Essayez de lister un dossier inexistant, redirigez l'erreur
ls /inexistant 2> erreur.txt

# 4. Vérifiez le contenu
cat erreur.txt

Exercise 2: Pipes

# 1. Comptez les fichiers dans /etc
ls /etc | wc -l

# 2. Trouvez les 5 plus gros fichiers de votre home
du -sh ~/* 2>/dev/null | sort -rh | head -5

# 3. Listez les utilisateurs uniques connectés
who | cut -d' ' -f1 | sort -u

Exercise 3: tee and xargs

# 1. Listez /etc, affichez et sauvegardez
ls /etc | tee etc_backup.txt

# 2. Créez 5 fichiers test avec xargs
echo "test1 test2 test3 test4 test5" | xargs touch

# 3. Vérifiez et supprimez
ls test*
echo "test1 test2 test3 test4 test5" | xargs rm

Exercise 4: Complete pipeline

# Analysez /etc/passwd :
# 1. Extrayez les noms d'utilisateur (premier champ)
# 2. Triez-les
# 3. Comptez-les

cat /etc/passwd | cut -d: -f1 | sort | wc -l

Quiz

Q1. How do you redirect stdout and stderr to the same file?

Answer

commande > fichier.txt 2>&1 or commande &> fichier.txt

Q2. What is /dev/null used for?

Answer

To ignore/discard output. Everything redirected to /dev/null disappears.

Q3. What is the difference between > and >>?

Answer

> overwrites the file, >> appends to the end of the file.

🔝 Back to table of contents



Key takeaways

  • stdin (0) = input, stdout (1) = output, stderr (2) = errors
  • > overwrites, >> appends
  • 2> redirects stderr, &> redirects everything
  • | connects stdout → stdin
  • /dev/null to ignore output
  • tee splits to a file AND the screen
  • xargs turns stdin into arguments

🔝 Back to table of contents


← Previous chapter | Next chapter: Review exercises →