Validate the number of arguments passed in bash from read

Viewed 89

I have a question about validating user input regarding number of arguments passed by the user in a bash script. For example, if I use:

if [[ $# -eq 2 ]]
then...

that will check if 2 arguments passed from the command line like this:

./somescript.sh arg1 arg2

but how to validate if user passed 2 arguments when asked? For example:

echo "Type 2 names:"
read...
if [[ user passed more || less than 2 arguments]]
   echo "incorrect number of names"

Now if I try to use $# -eq 2 it doesn't work.

What's the proper way to do it?

2 Answers

Use an array:

read -r -a array
if [[ "${#array[@]}" -eq 2 ]]; then ...

See output of:

declare -p array

Alternatively if your shell has no array like ksh or POSIX shell, you can populate the arguments from the read variable like this:

read -r reply
set -f # Disable globbing
set -- $reply # without quotes
if [ $# -eq 2 ]; then
Related