Counting variables in bash script using $#

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 2K views
jf22901
Messages
55
Reaction score
1
Hi all.

If I read in variables entered by the user, how can I check to make sure the correct number of variables were entered? For example, after reading in a data file and making it into an array, I have:

echo "To check the data, enter the first element number, last element number and step size as x y z:"
read x y z


It then goes on to start a loop, but what I would like now (before the loop) is a check to see if three variables have been entered, before the rest of the script continues. I've tried 'read $1 $2 $3' and 'read $x $y $z', but doing so results in echo "$#" = 0. I'm sure it's something simple, but I can't fathom it out. (In my defence, I did only learn bash scripting last week!)

I've attached a copy of the script as a text file in case the above makes no sense! The data file it reads is just a file of random numbers I am practising with.

Many thanks in advance!
 

Attachments

Physics news on Phys.org
Problem solved!

I have added '[ -z "$x" ] || [ -z "$y" ] || [ -z "$z" ]' to the if statement, to make sure x, y or z aren't null, and it seems to be working!