Standard streams & arguments

Introduction to Bash Scripting

Alex Scriven

Data Scientist

STDIN-STDOUT-STDERR

In Bash scripting, there are three 'streams' for your program:

  • STDIN (standard input). A stream of data into the program
  • STDOUT (standard output). A stream of data out of the program
  • STDERR (standard error). Errors in your program

By default, these streams will come from and write out to the terminal.

Though you may see 2> /dev/null in script calls; redirecting STDERR to be deleted. (1> /dev/null would be STDOUT)

Introduction to Bash Scripting

STDIN-STDOUT graphically

Here is a graphical representation of the standard streams, using the pipeline created previously:

Standard Streams diagram

Introduction to Bash Scripting

STDIN example

Consider a text file (sports.txt) with 3 lines of data.

football
basketball
swimming

The cat sports.txt 1> new_sports.txt command is an example of taking data from the file and writing STDOUT to a new file. See what happens if you cat new_sports.txt

football
basketball
swimming
Introduction to Bash Scripting

STDIN vs ARGV

A key concept in Bash scripting is arguments

Bash scripts can take arguments to be used inside by adding a space after the script execution call.

  • ARGV is the array of all the arguments given to the program.
  • Each argument can be accessed via the $ notation. The first as $1, the second as $2 etc.
  • $@ and $* give all the arguments in ARGV
  • $# gives the length (number) of arguments
Introduction to Bash Scripting

ARGV example

Consider an example script (args.sh):

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

Running the ARGV example

Now running 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 to Bash Scripting

Let's practice!

Introduction to Bash Scripting

Preparing Video For Download...