Вопрос

I am trying to verify if the input entered by the user is of a numeric type or non-numeric type. If numeric type then it will do the necessary operations else it will generate an error message of my design (not the standard error generated)

The steps that i have been using is:

1> perform a mathematical operation on the input.
echo -n "Enter a number : "; read a

now if the input a is of numeric type then the operation is a success else there will be a standard error generated.

Enter a number : ww

expr: non-numeric argument

The code that I have used in order to redirect the standard error is :

tmp=`expr $a / 1` >&2

I have also tried rediirecting it to the null file using the code:

tmp=`expr $a / 1` > /dev/null

But the error is still being displayed.

Это было полезно?

Решение 2

How about regex the input instead?

read a
if [[ $a =~ ^[0-9]+$ ]]
then
  echo this is a number
else
  echo not a number
fi
  • ^ means start of string
  • $ means end of string
  • [0-9]+ means 1 or more occurances of a number
  • =~ is syntax for Bash regular expression

Другие советы

you must redirect stderr within internal expression:

tmp=`expr $a / 1 2>/dev/null`

Both of your examples there are redirecting stdout, not stderr, because there is no qualifier before the >.

To throw away stderr, you need 2> /dev/null, because it's file descriptor 2. Also useful are 2>&1, to merge stderr onto stdout, and &> file, shorthand to redirect both stderr and stdout to the same file.

This page explains fairly well: http://www.tldp.org/LDP/abs/html/io-redirection.html

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top