This tutorial will guide you through the process of understanding and mastering BASH input and output handling. We will learn about reading user input, handling command line arguments, and redirecting output and input.
Step 1: Reading User Input (read)
The read command in BASH is used to read input from the user. This is often used in scripts to interact with the user.
`#!/bin/bash
read -p 'Enter your name: ' name
echo "Hello, $name"`Practice Exercise
Create a script that asks the user for their favorite color and then outputs a message using that color.
Show Solution
`#!/bin/bash
read -p 'Enter your favorite color: ' color
echo "Your favorite color is $color"`Step 2: Command Line Arguments ($1, $2, $@, $#)
Command line arguments are a way to control the behavior of a script from the command line. They are accessed using the variables $1, $2, etc., where the number corresponds to the position of the argument on the command line.
`#!/bin/bash
echo "First argument: $1"
echo "Second argument: $2"`Practice Exercise
Write a script that takes two numbers as arguments and returns their sum.
Show Solution
`#!/bin/bash
sum=$(($1 + $2))
echo "The sum is: $sum"`Step 3: Redirecting Output (>, >>)
Redirecting output allows you to control where the output of a command or script goes. The > operator redirects output, overwriting the destination, while the >> operator appends to the destination.
`#!/bin/bash
echo "This will overwrite" > file.txt
echo "This will append" >> file.txt`Practice Exercise
Create a script that redirects the output of the ls command to a file called directory_contents.txt
Show Solution
`#!/bin/bash
ls > directory_contents.txt`Step 4: Redirecting Input (>, &>)
Just as you can redirect output, you can also redirect input. The < operator redirects input, and 2>> and &> are used to redirect error messages.
`#!/bin/bash
cat < file.txt
echo "This is an error" 2>> error.txt`Practice Exercise
Create a script that takes input from a file and appends it to another file.
Show Solution
`#!/bin/bash
cat < input.txt >> output.txt`Sign in to take Cornell notes on this lesson — they save automatically and stay with your account.