1. Standard streams & arguments
Let's learn more about inputs and outputs for your Bash scripts.
2. STDIN-STDOUT-STDERR
It is also useful to know about the three streams for Bash programs.
Standard input is the stream of data going into the program.
Standard output is the stream going out,
and Standard error is where errors and exceptions in the program are written to.
By default this isn't obvious as the streams tend to appear in the terminal.
Though you may see scripts called with this bit of code at the end. This is redirecting the standard error to part of the UNIX system which deletes input. You could use the same using 1 to redirect stdout.
3. STDIN-STDOUT graphically
This graphical example represents what we just discussed conceptually.
The standard output of the cat program, becomes the standard input for the cut program and so on until the pipe finishes which prints the last standard output to the terminal.
This is the expected behaviour. Though if an error occurred at any time, the error would by default display in the terminal.
4. STDIN example
Consider this text file with three lines of data.
With this text file, running the cat command as seen will take the data from the file and redirect the STDOUT (the file contents) to a new file called new sports dot txt. The 1 means standard output.
You could cat the file created and see that indeed, the standard output of the first cat ended up in the new file.
5. STDIN vs ARGV
A key concept for Bash scripting is the use of arguments.
Bash scripts take arguments specified when making the execution call of the script.
ARGV is a term to describe all the arguments that are fed into the script.
You can access the arguments using numerical dollar-sign notation. The first argument being dollar-one etc.
Some other special arguments are dollar-at-symbol and dollar-star which return all the arguments together.
Dollar-hash gives the number of arguments.
6. ARGV example
Let's make this conceptual idea concrete. Consider a script with the following code inside.
We hope to print out the first then second arguments. Then all the arguments, then a phrase including how many arguments. Let's see how it goes.
7. Running the ARGV example
If we execute that script as noted here, the strings 'one two three four five' are all separate arguments.
Indeed, our return will be as we expected. We print out the first, then second, then all the arguments and finally our phrase containing the number of arguments (which is 5).
8. Let's practice!
Let's practice using arguments in our Bash scripts!