Value of variable is NULL, but test doesn't seem to recognize

Hello, Unix-forums!

My problem:

read -p "Enter any number, please" number
sleep 1
echo $number | tr -d 0-9
test -z $number && echo "Thank you" || echo "This is not a number"

Test always displays "This is not a number". It doesn't matter if I entered a or 1.

But if I order

echo $number

before the test command, it displays nothing, so the $number should be NULL, not?

Try:

read -p 'Enter any number, please: ' number
sleep 1
number=$( tr -d 0-9 <<< "$number" )
test -z "$number" && 
  echo "Thank you" || 
    echo "This is not a number"

Actually you could avoid calling external commands in this case:

read -p 'Enter any number, please: ' number
sleep 1
test -z "${number//[0-9]}" && 
  echo "Thank you" || 
    echo "This is not a number"

P.S. The code above uses non standard shell features, but that shouldn't be
a problem, considering that the original post uses non standard features too :slight_smile:

1 Like

Thank you. But can you tell me what's wrong with my code. I'd be really interested in that.

Edit: Solved. Looked closer to radoulov's syntax. You're my hero :slight_smile: