Bash: validating variables and parameters

This is a wiki page. Be bold and improve it!

If you have any questions about the content on this page, don't hesitate to open a new ticket and we'll do our best to assist you.

Table of Contents

Help us complete this page with more examples of validation.

Variables

The simplest validation is as follows:

if [[ "$variable" ]]; then
        echo "set"   
else
        echo "unset"
fi

It checks if a variable is set.

Beware, if you want to validate the value of the variable, you'll have to be more explicit:

variable=0
if [[ $variable ]]; then
        echo "This gets printed because the variable is set."   
elif [[ $variable == 1 ]]; then
        echo "This does not get printed because the variable equals 0."
fi

Strings

You can use the equal-tilde operator (=~) to test strings against a regular expression:

#!/bin/bash

if ! [[ "$1" =~ [^a-zA-Z0-9] ]]; then
  echo "$1 is NOT alphanumeric."
else
  echo "$1 is alphanumeric"
fi

Files

if [[ -e "$1" ]]
then
        echo "The file exists."
else
        echo "The file does not exist."
fi

See also

More

See section "6.4 Bash Conditional Expressions" of the official documentation:
http://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expre...