Bash Scripting for Beginners: Complete Guide to Getting Started - Data Streams (Part 11)
Introduction to Data Streams in Bash Scripting
Overview of Data Streams
- The lesson focuses on understanding data streams, specifically standard input, standard output, and standard error.
- These concepts are crucial not only for bash scripting but also have broader implications across Linux systems.
Types of Data Streams
- There are three types of data streams:
- Standard Output (stdout)
- Standard Error (stderr)
- Standard Input (stdin)
Understanding Standard Output and Standard Error
Distinction Between Outputs
- Standard Output is the result printed to the screen when a command executes successfully; it does not include errors.
- An example is using
echoto print "hello world," which results in a zero exit code indicating success.
Identifying Errors
- To identify errors, one can use
echo $?, which returns the exit code of the last executed command. A non-zero value indicates an error.
Practical Example with the Find Command
Using Find Command
- The
findcommand searches for files or directories based on specified criteria. It can produce both valid outputs and errors.
- When searching in restricted directories, permission denied errors may occur alongside valid file listings.
Redirecting Errors
- Using
sudowith commands likefindallows access to all files without permission issues, demonstrating how user permissions affect output.
Redirecting Standard Error to /dev/null
Suppressing Error Messages
- By redirecting stderr to
/dev/null, users can suppress error messages while still viewing valid outputs from commands.
/dev/nullacts as a black hole where any redirected content is discarded.
Redirecting Both Outputs
Combining Outputs into Files
- Users can redirect both stdout and stderr into separate files for better organization and troubleshooting.
- For instance, using
> output.txt 2> error.txtseparates successful outputs from errors during execution.
Implementing Redirection in Scripts
Updating Scripts for Logging
- Modifications were made to an updater script to log successful operations and errors separately into designated log files.
Checking Exit Codes in Scripts
- The script checks exit codes after executing commands to determine if they succeeded or failed, allowing appropriate logging actions based on outcomes.
Introduction to Standard Input
Capturing User Input
- The third type of data stream is standard input (stdin), which captures user input via commands like
read.
Example Script for User Interaction
- A simple script prompts users for their name and echoes it back as confirmation, illustrating how stdin works effectively within scripts.