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.
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
ksh and zsh and to even a lesser degree, bash. These are not reliable types - they will not suffice for input validation.