You want your script to check the value of some strings before using them. The strings could be user input, read from a file, or environment variables passed to your script. How do you do that with bash scripts?
There are some simple tests that you can do with the built-in
test command, using the single bracket if
statements. You can check to see whether a
variable has any text, and you can check to see whether two variables
are equal as strings.
For example:
#!/usr/bin/env bash # cookbook filename: checkstr # # if statement # test a string to see if it has any length # # use the command line argument VAR="$1" # if [ "$VAR" ] then echo has text else echo zero length fi # if [ -z "$VAR" ] then echo zero length else echo has text fi
We use the phrase “has any length” deliberately. There are two types of variables that will have no length—those that have been set to an empty string and those that have not been set at all. This test does not distinguish between those two cases. All it asks is whether there are some characters in the variable.
It is important to put quotes around the "$VAR"
expression
because without them your syntax could be disturbed by odd user input.
If the value of $VAR
were x -a 7 -lt 5
and if there were no quotes
around the $VAR
, then the
expression:
if [ -z $VAR ]
would become (after variable substitution):
if [ -z x -a 7 -lt 5 ]
which is legitimate syntax for a more elaborate test, but one that will yield a result that is not what you wanted (i.e., one not based on whether the string has characters).
3.141.199.243