1. Overview

Verifying the length of a variable can be important for handling data correctly, preventing invalid responses, or executing conditional statements based on a variable’s length. One example is checking that a username or password satisfy a minimum length requirement.

In this tutorial, we’ll explore different approaches for verifying the length of a variable in Bash.

2. Using Bash Parameter Expansion

To compute the length of a variable in Bash, we can use a built-in parameter expansion feature. We simply need to prepend a # symbol before the variable name within a brace expansion:

$ str='sysadmin'
$ echo "${#str}"
8

The str variable consists of the string sysadmin made up of exactly 8 characters, as the output from echo confirms. We have access to the length of the variable using the ${#str} syntax.

To validate whether the length of a variable is, for example, greater than six characters, we can use the test operator represented by the [] construct:

$ [ "${#str}" -gt 6 ] && echo 'valid' || echo 'invalid'
valid

In this case, we employ -gt to check if the length of the str variable is greater than 6. Then, we use the && and || logical operators to print valid if the test exits successfully, or invalid if the test fails.

3. Using expr length

Another approach is to compute the length of a variable using expr:

$ str='sysadmin'
$ expr length "$str"
8

Generally, the expr command evaluates expressions. By using the length option of expr, we can extract the length of a string.

When testing whether the length of the variable exceeds a given number of characters, we can use command substitution within the [] construct:

$ [ $(expr length "$str") -gt 6 ] && echo 'valid' || echo 'invalid'
valid

The value of $(expr length “$str”) is 8, which is greater than 6. Therefore, the test succeeds, and the word valid is printed.

4. Using echo and wc

We can also use the wc command in conjunction with echo -n to evaluate the length of a variable:

$ str='sysadmin'
$ echo -n "$str" | wc -c
8

The wc -c command counts the number of characters, hence providing the length of the variable. The -n switch used with echo instructs the command to not output a trailing newline character at the end of lines. This way, we avoid counting the newline character as part of the string.

Then, we can wrap the expression within $() using command substitution and test the length in a more complex expression:

$ [ $(echo -n "$str" | wc -c) -gt 6 ] && echo 'valid' || echo 'invalid'
valid

The test succeeds, and the str variable is considered valid.

5. Using grep and wc

Another method to calculate the length of a variable uses grep and wc. In particular, we first run grep to output the characters of the string, one per line:

$ str='sysadmin'
$ grep -o '.' <<< "$str"
s
y
s
a
d
m
i
n

The -o option used with grep extracts the exact match found, instead of the entire line. The matched pattern in this case is a single character, represented by a regex dot.

Next, we pipe the result to wc -l:

$ grep -o '.' <<< "$str" | wc -l
8

The -l option with wc counts the number of lines in the provided input. Since each character is on a separate line, wc -l gives the number of characters in the string.

Therefore, we can now use command substitution to conduct the test:

$ [ $(grep -o '.' <<< "$str" | wc -l) -gt 6 ] && echo 'valid' || echo 'invalid'
valid

The test succeeds as expected, indicating that the str variable is valid as per our conditions.

6. Using grep and Regex

Alternatively, we can use grep to match a regex pattern consisting of seven or more characters:

$ str='sysadmin'
$ grep -Eo '^.{7,}$' <<< "$str" &> /dev/null && echo 'valid' || echo 'invalid'
valid

The -E option used with grep enables extended regex, while the -o option extracts an exact match. The pattern in this case begins with 7 or more characters before ending.

Notably, we also redirect stdout and stderr to the null device so as not to display any output from grep.

7. Using the [[]] Construct

Instead of using grep to match a regex, we can use the [[]] construct to test against the same regex:

$ str='sysadmin'
$ [[ "$str" =~ ^.{7,}$ ]] && echo 'valid' || echo 'invalid'
valid

Since the str string is 7 characters or longer, a match is found, and the test succeeds.

8. Using awk

Another approach to computing the length of a variable is via awk:

$ str='sysadmin'
$ echo "$str" | awk '{print length}'
8

Here, we use the print and length built-in functions within awk to print the length of the input line. The awk expression is equivalent to awk ‘{print length($0)}’ where $0 represents the entire line.

Finally, we can use command substitution to wrap the entire expression and conduct the required test:

$ [ $(echo "$str" | awk '{print length}') -gt 6 ] && echo 'valid' || echo 'invalid'
valid

As before, since the str variable is of length greater than 6, the test succeeds and prints out the word valid.

9. Using a case Statement

We can also use a case statement in Bash along with globbing to test whether the length of a variable is valid according to given conditions:

$ cat varlen.sh
#!/usr/bin/env bash
str='sysadmin'
case "$str" in
    ???????*) echo 'valid'   ;;
           *) echo 'invalid' ;;
esac

The varlen.sh script contains a simple case statement that matches the str variable against a specific expression. In the context of globbing, the expression consists of exactly seven characters followed by any number of characters, as indicated by the ???????* syntax.

If a match is found, the word valid is printed. Otherwise, invalid is printed.

Next, let’s grant the script execute permissions via chmod:

$ chmod +x varlen.sh

Finally, we run the script:

$ ./varlen.sh
valid

The result shows that we’ve found a string with a length of at least seven characters.

10. Conclusion

In this article, we explored several methods for computing and verifying the length of a variable in Bash. In particular, the methods included using a built-in parameter expansion feature in Bash, as well as using expr length, echo -n and wc, grep and wc, grep and regex, the [[]] construct, awk, and case statements.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.