Testing for String Characteristics
Problem
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?
Solution
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.
Discussion
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
fiWe 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access