I want to make an input constraint on read:

Terminal Shell;

read x
read y
echo $(($x+$y))

I want to make a constraint of x, I want x to be -100 <= x <= 100.
What's the command I insert before read x?


$x is a string. A user may enter anything, it isn't necessarily a number. Input validation comes after input. You have to check if it is an integer, and then you can do arithmetic comparison. For instance

read x
#validate if it is an integer
[[ "$x" =~ -?[0-9]+ ]] || echo error
#validate range (this is better done algebraically, not with string manipulation)
(( x >= -100 && x <= 100 )) || echo error
# carry on

by the way, the arithmetic evaluation expression in $(( ... )) can use variable names, not variable expansions. Just write $(( x + y )).

Solution for puritans:

x=$(awk '/^-?[0-9]+\s*$/{ if ($1<=100 && $1>=-100){ print; exit; } } { exit 1; }') || echo error

In this case, awk reads the input, not the shell, but you can also do it with read and then filter the result. Instead of echo error, you can use the expression in a loop (that re-prompts user for another input), or just bail out with exit 1.

  • This is only likely to work in a few shells, and does not use standard syntax.
    – mikeserv
    Feb 4 '15 at 8:19
  • What do you mean by standard syntax? Bourne-compatible shell? This one is clean, it works in bash, which probably covers more than 95% cases, and will probably work for OP. If it doesn't, we can further discuss uglier variants.
    – orion
    Feb 4 '15 at 8:23
  • No, I mean standard - IEEE specified. According to POSIX.
    – mikeserv
    Feb 4 '15 at 8:24

You can't do this before read x - you haven't yet read it. How can you test the unknown? The only solution is to get the data, then test it. That, however, can be done:

case ${#x}${x##?*[!0-9]*} in 
(?|[!1-4]*|4[!-]*|1-*|?[!-0-9]*) ! :;;
(*) echo "$(( x + y ))";;esac
  • Can i declare $x first? (By declare i mean like c++ and python). So that i want the integer input to be in that range.. Anyway, i havent tried the ones you both suggested . Still away from home. Ill tell you if it works.
    – Fadh Nhz
    Feb 4 '15 at 8:28
  • @FadhNhz - ahh - so you're asking about types? Well, in general, no. Some shells implement loose types - ksh and zsh and to even a lesser degree, bash. These are not reliable types - they will not suffice for input validation.
    – mikeserv
    Feb 4 '15 at 8:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.