Bash variable existence check
From Linux Shell Scripting Tutorial - A Beginner's handbook
- 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.shSample outputs:
./varcheck.sh: line 3: 1: Error command line argument not passed