Stream standard e argomenti

Introduzione al Bash Scripting

Alex Scriven

Data Scientist

STDIN-STDOUT-STDERR

Nel Bash scripting, ci sono tre "stream" per il programma:

  • STDIN (standard input). Flusso di dati in ingresso
  • STDOUT (standard output). Flusso di dati in uscita
  • STDERR (standard error). Errori del programma

Per impostazione predefinita, questi stream leggono e scrivono dal terminale.

Puoi vedere 2> /dev/null nelle chiamate: reindirizza STDERR per eliminarlo. (1> /dev/null è STDOUT)

Introduzione al Bash Scripting

STDIN-STDOUT graficamente

Rappresentazione grafica degli stream standard, usando la pipeline creata prima:

Diagramma degli stream standard

Introduzione al Bash Scripting

Esempio di STDIN

Considera un file di testo (sports.txt) con 3 righe.

football
basketball
swimming

Il comando cat sports.txt 1> new_sports.txt legge dal file e scrive lo STDOUT in un nuovo file. Prova cat new_sports.txt

football
basketball
swimming
Introduzione al Bash Scripting

STDIN vs ARGV

Un concetto chiave in Bash è quello degli argomenti

Gli script Bash possono accettare argomenti aggiungendo uno spazio dopo il comando.

  • ARGV è l'array di tutti gli argomenti passati al programma.
  • Ogni argomento è accessibile con la notazione $: il primo è $1, il secondo $2, ecc.
  • $@ e $* restituiscono tutti gli argomenti in ARGV
  • $# restituisce il numero di argomenti
Introduzione al Bash Scripting

Esempio ARGV

Considera uno script di esempio (args.sh):

#!/usr/bash
echo $1
echo $2
echo $@
echo "There are " $# "arguments"
Introduzione al Bash Scripting

Eseguire l'esempio ARGV

Ora esegui bash args.sh one two three four five

one
two
one two three four five
Ci sono 5 argomenti

 

#!/usr/bash
echo $1
echo $2
echo $@
echo "There are " $# "arguments"
Introduzione al Bash Scripting

Passons à la pratique !

Introduzione al Bash Scripting

Preparing Video For Download...