Bash scripts allow developers to automate tasks and processes on Linux systems. A key part of many scripts involves taking input from users to drive logic and decisions. Bash provides several ways to read user input, with advantages and use cases for each method.
Read Command
The read command is the most common way to accept input in a Bash script. It stops script execution, waits for user input, and assigns that input to a variable for later use.
Here is a simple example:
#!/bin/bashread -p "Enter your name: " name echo "Hello $name, nice to meet you!"
The -p option prints a prompt string. This script will stop and wait for the user to enter their name, which gets stored in the $name variable. The script echoes a greeting with the name they entered.
Some key points on read:
- It can accept single or multiple inputs on one line
- There are options like -s for silent/hidden input e.g. for passwords
- -n sets a max character count for input
- -t sets a timeout period for input
Overall, read is great for simple input needs.
Command Substitution
Command substitution allows capturing the output of a command as a variable value with either $( ) or backticks.
For example:
#!/bin/bashname=$(whoami) date=$(date)
echo "User is: $name" echo "Current date is: $date"
This runs whoami and date, storing each output in a variable to reuse.
Benefits include:
- No script pausing for input
- Can process outputs of other commands
Downsides are no input prompts or control of the input process.
Pass Script Arguments
Bash scripts can also directly accept command line arguments on execution:
#!/bin/bashname=$1 date=$2
echo "User is: $name"
echo "Date is: $date"
To run it:
$ ./script.sh "John" "2023-02-15"
$1, $2, etc store the given parameters as variables.
Benefits are simplicity and no pausing for input. Downsides are lacking prompts and input validation.
When to Use Each Method
In summary:
- Use read for interactive user input
- Use command substitution to reuse outputs
- Use script arguments for simple hard-coded values
The method you choose depends on if you need dynamic vs fixed input, and interactivity vs automation.
Conclusion
Bash provides flexible options for user input including read, command substitution, and script arguments. Choose the right approach based on your script‘s specific input requirements. Mastering user input unlocks the ability to write sophisticated Bash automation scripts.