The following section of your code:
echo $num | grep -i [^0-9+-]
if ["$?" = 1] then
Should be changed to this:
if grep -q '[^0-9+-]' <<< "$num"; then
Inside a test ([
), spaces are important but there's no need to use it here anyway. Using -q
means that grep doesn't produce output - the exit status indicates whether a match was found or not, so it can be used directly with if
.
As mentioned in the comments, the pattern to match a valid integer could be made more robust. Some good ways to detect an integer are shown in this related question. For example, you could change your grep pattern to something like this:
grep -qE '^[+-]?(0|[1-9][0-9]*)$'
or use native regular expressions, as in the most popular answer to that question:
re='^[+-]?(0|[1-9][0-9]*)$'
if [[ $num =~ $re ]]; then
sum=$((sum + num))
else
echo "Sorry, '$num' is not a number"
fi
Even this pattern isn't perfect, as it will fail for numbers starting with leading 0
s, among other things.