Bash variable existence check

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Create the constants variableHomeCustomize the bash shell environments →
  • If the variable is not defined, you can stop executing the Bash script with the following syntax:
${varName?Error varName is not defined}
${varName:?Error varName is not defined or is empty}
  • This is useful for a sanity checking
  • The script will stop executing if the variable is not defined.

Example

  • Create a shell script called varcheck.sh:
#!/bin/bash
# varcheck.sh: Variable sanity check with :? 
path=${1:?Error command line argument not passed}
 
echo "Backup path is $path."
echo "I'm done if \$path is set."

Run it as follows:

chmod +x varcheck.sh
./varcheck.sh /home

Sample outputs:

Backup path is /home.
I'm done if $path is set.

Run the script without any arguments:

./varcheck.sh

Sample outputs:

./varcheck.sh: line 3: 1: Error command line argument not passed
← Create the constants variableHomeCustomize the bash shell environments →