Unix How-To: Checking Responses with ckrange

One of the all too common coding mistakes leading to security vulnerabilities is the failure to validate all entered data for accuracy. A defensive developer will consider all input to be evil until proven otherwise. Anyone writing scripts on Solaris has a leg up when it comes to input validation -- the versatile and wonderfully handy ckrange command.

The ckrange (check range) command essentially does just that. It checks data entered by a user against criteria determined to ensure that it meets the requirements of the script.

Enter a ckrange command to ensure a value entered is between 1 and 10 and you'll see that the command both provides a prompt and asks again if the response lies outside the specified range.

$ ckrange -l 1 -u 10

Enter an integer between 1 and 10 [1-10,?,q] 11
        ERROR: Please enter an integer between 1 and 10.

Enter an integer between 1 and 10 [1-10,?,q] a
        ERROR: Please enter an integer between 1 and 10.

Enter an integer between 1 and 10 [1-10,?,q]

Once you provide ckrange with an appropriate answer, it stops asking.

Assuming you want to grab whatever response has been entered and use it for something, you can assign it to a variable like this:

$ ans=`ckrange -l 1 -u 10`

Enter an integer between 1 and 10 [1-10,?,q] 4
$ echo $ans

If you want to set a default (i.e., the value you use if the user presses return instead of entering a number), you can do so with the -d option. Here's an example:

$ ckrange -d 11 -l 1 -u 100

Enter an integer between 1 and 100 [1-100,?,q]

If you use ckrange without any arguments, it provides an enormous numeric range -- all the numbers between -2,147,483,648 and +2,147,483,647. That's more than 4 1/4 billion possible values.

$ ckrange

Enter an integer between -2147483648 and
2147483647 [-2147483648-2147483647,?,q]

Respond with a number outside of this range and ckrange reduces it to whichever end of its range limit is closest (i.e., either -2147483648 or +2147483647).

$ ckrange

Enter an integer between -2147483648 and
2147483647 [-2147483648-2147483647,?,q] 8503805830485098340

You can even use ckrange to translate data from one numeric base to another. Specifying your base as 16, for example, you can convert hexadecimal to decimal as shown in this example:

$ ckrange -b 16

Enter a base 16 integer between -2147483648 and
2147483647 [-2147483648-2147483647,?,q] ff

Since ckrange prompts, loops (as needed) and checks the range of data entered, it saves you a lot of troublesome shell commands. The ckrange and ckyorn (check yes or no) commands in Solaris are very handy and wonderfully easy to use.

This article is published as part of the IDG Contributor Network. Want to Join?

The brave new world of Windows 10 license activation
View Comments
Join the discussion
Be the first to comment on this article. Our Commenting Policies