0

I have this set of example here to test if the user has keyed in any data after he presses enter.

echo -n "Type a digit or a letter > "
read character
blank=""
if  [ "$character" != "$blank"]; then
        echo "You typed something"
else
    echo "Enter something"
fi

The code above should be testing if the variable contains anything, but I can't seem to get it to work, any help ? Much appreciated.

Zac
  • 519
  • 3
  • 11
  • 17
  • 1
    See the [ -n STRING ] test: http://mywiki.wooledge.org/BashGuide/TestsAndConditionals ... – jasonwryan Jan 08 '15 at 16:32
  • [] should be separated by spaces from other symbols: [ "$character" != "$blank" ] But much better use -n options fortest – Costas Jan 08 '15 at 16:33

1 Answers1

0

You can simply use [ "$character" ] to test if string is nonzero, what is equivalent of longer form [ -n "$character" ]. Alternatively [ -z $character ] to test if string is zero.

However many times in interactive scripts what is really needed is to set some default value in the variable which user can override. If this is your intention then you can avoid test and use parameter expansion:

read character
echo "character is set to ${character:-default}"
jimmij
  • 47,140