read (Standard Input)

The read command is the command in shell scripting for reading from standard in. In its most basic form, you can merely prompt the user for input.

#!/bin/bash

echo "Please enter your name"
read name
echo "Hello, $name. How are you?"

For more advanced usage, you can use it in a while statement to read data from standard input line-by-line.

#!/bin/bash

while read line
do
    echo "The next line from standard in is: $line"
done

The output of the above script is shown here:

$ cat TestFile
Cool Beans
This is
a test.

$ cat TestFile | ./TestScript.sh
The next line from standard in is: Cool Beans
The next line from standard in is: This is
The next line from standard in is: a test.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License