• Home
  • Shell
    • Emacs
    • Perl
    • screen
    • sed
  • Ubuntu
    • VNC
  • Web Development
    • Javascript
    • Joomla
    • MySQL
    • osTicket
  • Windows
    • Gimp

BASH> Variable checking

Nov11
2010
Written by Scott Rowley

Check the variable is a whole number

if [ $VARIABLE -eq $VARIABLE 2> /dev/null ]; then
echo $VARIABLE is a number
else
echo $VARIABLE is not a number
fi

Check the variable is not empty

if [ $VARIABLE != "" ] ; then
<code_to_execute>
else
echo "Error: VARIABLE is empty"
fi

or as provided by solstice:

if [ -z "$VARIABLE" ] ; then
echo “VARIABLE is empty”
else
echo “VARIABLE is not empty”
fi

or -n to test if it”s not null

if [ -n "$VARIABLE" ] ; then
echo “VARIABLE is not empty”
else
echo “VARIABLE is empty”
fi

Check the variable is alpha only

if [[ "$VARIABLE" =~ ^[a-zA-Z]+$ ]] ; then
echo "Variable contains letters only"
else
echo "Error"
fi
Posted in BASH
« osTicket> Send reply to alternate/additional email address(es).
» BASH> ‘find’ examples

2 Comments

  1. solstice's Gravatar solstice
    November 21, 2010 at 12:24 pm

    to check for an empty variable, you can use -z
    if [ -z “$VARIABLE” ] ; then
    echo “$VARIABLE is empty”
    else
    echo “$VARIABLE is not empty”
    fi

    or -n to test if it”s not null
    if [ -n “$VARIABLE” ] ; then
    echo “$VARIABLE is not empty”
    else
    echo “$VARIABLE is empty”
    fi

    -n can be confusing so I stick with -z only.

  2. scottro's Gravatar scottro
    November 22, 2010 at 8:07 pm

    Thanks soltstice, I’ll add when I’m back at my desk 😉

Corrections? Questions? Comments?

Find an error?
Everything work out great for you?
Have some feedback?
Like to see something added to the article?

PLEASE leave us a comment after the article and let us know how we are doing, or if something needs corrected, improved or clarified.

Thank you!
- The Management

Advertisement

Sudo Bash
By Geeks - For Geeks

Back to Top