Shell Script: Count Variable Length

Objective: Count the number of characters in a shell variable.

If you are using bash shell, parameter expansion can be used to get the length. If not, the wc or awk utilities can be used. So, let’s say that we want to count the number of characters in the variable $var.

To count the number of characters using wc, use the following syntax.

Make sure that the “-n” option is specified to the echo command, else wc will count the newline character as well. Note that spaces are counted as characters as well.

To count the number of characters using awk, use the following syntax.

This time round, the “-n” option need not be specified for the echo command.

On POSIX shells (bash, ksh, etc) use parameter expansion to get the string length.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }