Interacting with users is a crucial aspect of Bash scripting. In this section, we'll explore how to handle user input and output, enabling your scripts to become more interactive and user-friendly.
Bash provides the read
command to accept user input. This command stores the user's input in a variable, which can then be used in the script.
echo "What is your name?"
read name
echo "Hello, $name!"
You can also set a prompt for the read
command:
read -p "What is your age? " age
echo "You are $age years old."
Handling Command-Line Arguments
Bash scripts can also accept command-line arguments, which are accessed using the special variables $1
, $2
, $3
, and so on. These variables represent the first, second, third, and subsequent arguments passed to the script.
#!/bin/bash
echo "The first argument is: $1"
echo "The second argument is: $2"
To run this script, you would execute it like this:
./script.sh "LabEx" "Example"
Printing Output
Bash provides several ways to print output, including:
echo
: Display text or the value of variables
printf
: Format and print output, similar to the printf()
function in C
cat
: Concatenate and display the contents of files
echo "This is a message."
printf "The value of pi is: %.2f\n" 3.14159
cat example.txt
Bash allows you to redirect input and output using special characters, such as >
(redirect output to a file), <
(redirect input from a file), and |
(pipe the output of one command to the input of another).
## Redirect output to a file
echo "Hello, LabEx!" > output.txt
## Redirect input from a file
cat < input.txt
## Pipe output to another command
ls | grep "example"
By understanding how to handle user input and output, you can create Bash scripts that are more interactive and user-friendly. In the next section, we'll explore creating and using functions.