Naptime
Naptime

Reputation: 3

Verifying bash script inputs

I'm writing some very simple Bash scripts and I've become a tad bit stuck.

I would like the script I'm attempting to write to be able to differentiate between "non valid inputs ie letters" from "valid inputs ie numbers from a specific range"

Currently the script "works" although I'm having troubles with another echo that I would like only to "echo" when the below line is "not true", is there a simple way to write this? I'm not specifically looking for efficient code, just code that I can learn from and understand at my amateur level.

So, long story short, is it possible to obtain information from the command line below, so that I can have a simple "not true" variable that I can use in another "else" or "elif" command?

For reference line 1 is to detect alphabetical inputs, and line 2 being the line of code I would like to write as "not true" for use in another part of my script.

  1. let xx=$a+1-1 2>/dev/null; ret=$?

  2. if [ $a -ge 7 ] && [ $a -le 70 ] && [ $xx -eq $xx ] && [ $ret -eq 0 ]

Upvotes: 0

Views: 285

Answers (2)

Paul Hodges
Paul Hodges

Reputation: 15246

If I read it right:

typeset -i xx # accepts only digits now.

If the input is foo, the value defaults to 0, so now just check the range.

if (( xx >= 7 && xx <= 70 )); then : value is ok
else echo "Value must be a number from 7 to 70"
     exit 1
fi

I also recommend the following useful resources: the Bash manual and the BashFAQs.

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246744

One problem with the "variable with integer attribute" is that it still doesn't protect you from invalid input:

$ declare -i aNumber
$ aNumber=1234X
bash: 1234X: value too great for base (error token is "1234X")

See 6.5 Shell Arithmetic for how bash interprets values to be numbers (scroll down to the paragraph starting with "Integer constants follow the C language definition")

In my experience, the best way to check for valid numeric input is with string-oriented pattern matching.

if [[ $1 =~ ^[+-]?[0-9]+$ ]]; then
    echo "input $1 is an integer"
fi

In addition to extended regular expressions, bash's advanced pattern matching can also be used within [[...]]

if [[ $1 == ?([+-])+([0-9]) ]]; then
    echo "input $1 is an integer"
fi

((...)) is preferred over let. See the let builtin command for details. Also the shellcheck wiki entry.

Upvotes: 0

Related Questions