Counting variables in bash script using $#

Click For Summary
SUMMARY

The discussion focuses on validating user input in a Bash script by ensuring that three variables are entered. The user initially struggled with checking the number of variables using '$#' and incorrect read commands. The solution involved adding a conditional statement '[ -z "$x" ] || [ -z "$y" ] || [ -z "$z" ]' to verify that none of the variables are null before proceeding with the script. This approach effectively ensures that the required input is provided.

PREREQUISITES
  • Basic understanding of Bash scripting
  • Familiarity with conditional statements in Bash
  • Knowledge of the 'read' command in Bash
  • Understanding of variable handling in shell scripts
NEXT STEPS
  • Explore advanced Bash scripting techniques for input validation
  • Learn about using arrays in Bash for handling multiple inputs
  • Investigate error handling in Bash scripts
  • Study the use of 'getopts' for parsing command-line options in Bash
USEFUL FOR

Bash script developers, system administrators, and anyone looking to improve their skills in input validation and error handling in shell scripting.

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!
 

Similar threads

  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 19 ·
Replies
19
Views
2K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 13 ·
Replies
13
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 11 ·
Replies
11
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 75 ·
3
Replies
75
Views
7K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 13 ·
Replies
13
Views
2K