Counting variables in bash script using $#

AI Thread Summary
The discussion revolves around validating user input in a bash script to ensure that three variables are entered correctly before proceeding with further execution. The user initially struggles with checking if the correct number of variables has been provided after reading input. They attempted various methods to validate the input but encountered issues. Ultimately, the solution was found by incorporating a conditional check using '[ -z "$x" ] || [ -z "$y" ] || [ -z "$z" ]' in an if statement to confirm that none of the variables are empty. This successfully resolved the issue, allowing the script to continue only when all three variables are provided.
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

Technology 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!
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...
Back
Top