Results 1 to 10 of 10
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 ...
- 11-13-2010 #1Just Joined!
- Join Date
- Nov 2010
- Location
- England
- Posts
- 5
[SOLVED] Counting variables in bash script
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 specifying the variables as $1, $2 and $3, but if I echo $#, the value comes out as zero, so it's obviously not working.
Can anyone please offer any help?
Thanks in advance,
Jack
- 11-13-2010 #2
Since you're reading x y z wouldn't you have to use $x $y and $z? $1 $2 and $3 would be if they're entered on the command line with the script name.
HTH
- 11-13-2010 #3Just Joined!
- Join Date
- Nov 2010
- Location
- England
- Posts
- 5
Hi barriehie
Do you mean like this (for example):
#!/bin/bash
echo "Enter the first element number, last element number and step size as x y z:"
read $x $y $z
echo "$#"
I have tried this method too, but it still won't 'count' the number of variables. 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!)
- 11-13-2010 #4
More like:
Since you're not entering anything on the CLI after the script name then $# will be 0; $0 will contain the script name.Code:read x y z
To test whether or not x, y, and z were all entered you'll have to test them against being NULL.
$0 = ./scriptnameCode:./scriptname value1 value2 value3
$1 = value1
$2 = value2
$3 = value3
etc., etc., etc.
- 11-14-2010 #5Just Joined!
- Join Date
- Nov 2010
- Location
- England
- Posts
- 5
Thanks barriehie.
I have now added the following, which tests to make sure neither x, y nor z are null.:
if [ -z "$x" ] || [ -z "$y" ] || [ -z "$z" ]; then
echo "Error: Run script again and enter search parameters correctly" && exit
fi
It seems to be working, so I'll leave it at that!
- 11-14-2010 #6
- 11-16-2010 #7
- 11-16-2010 #8Just Joined!
- Join Date
- Nov 2010
- Location
- England
- Posts
- 5
- 11-17-2010 #9
- 11-17-2010 #10Just Joined!
- Join Date
- Nov 2010
- Location
- England
- Posts
- 5
Done.
Thanks for all your help!




