The short answer is that you can't. You need to tell read
how many arguments it should expect, it will only read as much as you tell it to. If you give it just one variable name, it will read everything into that variable. If you give it more than one, for example 3, it will read everything until the first space (or tab, or newline or anything else you have set in $IFS
) into the 1st, everything to the next into the second and the rest of the line into the third. To illustrate:
$ cat file
one two three four five
$ while read line; do echo "$line"; done < file
one two three four five
$ while read first second rest; do echo "First: $first, Second:$second Rest:$rest"; done < file
First: one, Second:two Rest:three four five
So, read
will read as many variables as you give it. If you can have variable length input, you will either need to test each to find out how many were passed as explained in @Jobim's answer, or you can use arrays.
As explained in help read
:
Options:
-a array assign the words read to sequential indices of the array
variable ARRAY, starting at zero
This means that you can store the input values in an array and then get the length of the array with ${#ArrayName[@]}
:
#!/usr/bin/env bash
read -a values -p "please input values: "
echo "You gave ${#values[@]} value(s)"