Flux standard et arguments

Introduction au scripting Bash

Alex Scriven

Data Scientist

STDIN-STDOUT-STDERR

En script Bash, votre programme a trois « flux » :

  • STDIN (entrée standard). Un flux de données vers le programme
  • STDOUT (sortie standard). Un flux de données sortant du programme
  • STDERR (erreur standard). Les erreurs de votre programme

Par défaut, ces flux lisent et écrivent dans le terminal.

Vous verrez parfois 2> /dev/null dans des appels : on redirige STDERR pour le supprimer. (1> /dev/null serait STDOUT)

Introduction au scripting Bash

STDIN-STDOUT en graphique

Voici une représentation graphique des flux standard, avec le pipeline créé précédemment :

Schéma des flux standard

Introduction au scripting Bash

Exemple STDIN

Prenez un fichier texte (sports.txt) avec 3 lignes.

football
basketball
swimming

La commande cat sports.txt 1> new_sports.txt lit les données du fichier et écrit STDOUT dans un nouveau fichier. Voyez le résultat avec cat new_sports.txt

football
basketball
swimming
Introduction au scripting Bash

STDIN vs ARGV

Un concept clé en Bash : les arguments

Les scripts Bash peuvent prendre des arguments, ajoutés après l'appel d'exécution du script.

  • ARGV est le tableau de tous les arguments passés au programme.
  • Chaque argument est accessible via la notation $ : le premier $1, le second $2, etc.
  • $@ et $* renvoient tous les arguments d'ARGV
  • $# renvoie le nombre d'arguments
Introduction au scripting Bash

Exemple ARGV

Considérez un script d'exemple (args.sh) :

#!/usr/bash
echo $1
echo $2
echo $@
echo "There are " $# "arguments"
Introduction au scripting Bash

Exécuter l'exemple ARGV

Exécutons bash args.sh one two three four five

one
two
one two three four five
There are 5 arguments

 

#!/usr/bash
echo $1
echo $2
echo $@
echo "There are " $# "arguments"
Introduction au scripting Bash

Passons à la pratique !

Introduction au scripting Bash

Preparing Video For Download...