Reading from STDIN in bash

Reading from STDIN (Standard Input) in Bash allows you to accept user input or process data entered via the keyboard or piped from another command. You can use various techniques to read input from STDIN within a Bash script.

  1. Using the read command: The read command reads a line of input from STDIN and assigns it to a variable. Here’s an example:
#!/bin/bash

echo "Enter your name:"
read name

echo "Hello, $name!"

When executing this script, it prompts the user to enter their name. The read command captures the input and assigns it to the name variable. The script then displays a greeting using the provided name.

2. Piping input from another command: You can also read input from STDIN by piping the output of another command as input. For example:

#!/bin/bash

echo "Enter a number:"
read number

echo "The number multiplied by 2 is:"
echo "$number" | awk '{print $1 * 2}'

In this script, the read command reads a number from the user. The script then uses echo to pass the number as input to the awk command, which multiplies it by 2 and outputs the result.

3. Reading input in a loop: You can read multiple lines of input from STDIN using a loop. For example:

#!/bin/bash

echo "Enter multiple lines of text (press Ctrl+D to finish):"

while read line; do
  echo "You entered: $line"
done
  1. In this script, the while loop reads input line by line until the user signals the end of input by pressing Ctrl+D. Each line is stored in the line variable, and the script echoes it back.

These are just a few examples of how you can read input from STDIN in Bash. Depending on your script’s requirements, you can choose the appropriate method to handle user input or process data from STDIN.

Leave a Comment

Your email address will not be published. Required fields are marked *