read command examples
read command is useful in scripts when reading an input from user. This read command is used when the script want to interact with user for his inputs.
read command syntax read VARIABLE
Example1:Read a value from user input.
read VAR1
To display this value we have to use echo command.
echo $VAR1
Example2: Reading two words/variable/values at a time.
read VAR1 VAR2
Example3: Reading multiple values at a time.
read VAR1 VAR2 VAR3 VAR4
Example4: Read values in to an Array
read VAR1
ARR1=(VAR1)
to display first value in array use below command
echo ${ARR1[0]}
Example5: Read values from a command
read VAR1 VAR2 VAR3 << ( echo surendra kumar anne )
echo "Enter values are $VAR1 $VAR2 $VAR3"
Example6: Read user input and give some info to user what he have to give. For this use -p option to display some info when reading value.
read -p "Please enter 1 to 10 numbers: " VAL1
Note: You no need to echo command to display information to user, you can achieve that one using read -p option.
Example7: Read have inbuilt variable called REPLY. this is system variable which stores read value in to $REPLY.
read -p "Please enter a value"
echo "Enter value is $REPLY"
Please share your thoughts on this.
I have always found it useful to have an extra variable (I usually use JUNK) to catch any extra input.
eg
read VAR1 VAR2 VAR3 JUNK
if [[ -n $JUNK ]];then
echo Error: expecting 3 values
exit 1
fi
good Joe,
Appreciate your example. keep visiting linuxnix.com