Skip to content
Advertisement

Need help to this bash/shell exercise

#!/bin/bash
read x
if expr $x+1 1> /dev/null 2>&1
then
  echo "$x is a number" 
else 
  echo "$x is not a number" 
fi

The output of this line if expr $x+1 1> /dev/null 2>&1 I really don’t figure out how things go there…

Advertisement

Answer

Modify your script like this (simple add spaces around the +):

#!/bin/bash
read x
if expr $x + 1 1>/dev/null 2>&1
then
    echo "$x is a number"
else
    echo "$x is not a number"
fi

expr tries to add 1 to the value of the variable. If the status is 0 (value of $?) it is a number. Otherwise, there is an error, so it returns 1 (value of $? again).

If you remove the redirections of the output (1>/dev/null 2>&1) you will see that expr e + 1 outputs expr: non-integer argument.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement