Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash standard error redirection

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.

like image 924
debal Avatar asked Jun 18 '26 15:06

debal


2 Answers

you must redirect stderr within internal expression:

tmp=`expr $a / 1 2>/dev/null`
like image 106
loentar Avatar answered Jun 23 '26 02:06

loentar


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
like image 44
Zombo Avatar answered Jun 23 '26 03:06

Zombo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!