16

I have written this to find the length of the string, but it doesn't show the length of the string.

Is there something wrong with what I have written? I'm just a beginner in bash.

Str=abcdefghj

echo "Str is:" `expr length $Str` "characters long"
Ben
  • 54,723
  • 49
  • 178
  • 224
user2443218
  • 167
  • 1
  • 1
  • 4
  • 1
    There's nothing wrong with what you've written, but it is likely that the implementation of `expr` that you are using does not support the `length` argument. From the standard for `expr`: "The use of string arguments length, substr, index, or match produces unspecified results." – William Pursell Oct 05 '17 at 18:47
  • If your shell is Bash, there should basically never be any reason to use `expr`. It is necessary and useful in `sh` which has much more limited shell builtin facilities for arithmetic and string manipulation. – tripleee Oct 02 '21 at 08:37

3 Answers3

28

This can be done natively in bash, no need to resort to expr

echo ${#Str}
iruvar
  • 22,736
  • 7
  • 53
  • 82
  • 1
    `${#Str}` counts characters based on local, same as `echo -n $Str | wc -m`. To get the size in bytes set the local to C, `LC_ALL=C echo ${#Str}` – Phernost Aug 27 '18 at 16:02
2

Here is couple of ways to calculate length of variable :

echo ${#Str}
echo -n $Str | wc -m
echo -n $Str | wc -c
printf $Str | wc -m
expr length $Str
expr $Str : '.*'

Reference: http://techopsbook.blogspot.in/2017/09/how-to-find-length-of-string-variable.html

https://youtu.be/J6-Fkkj7f_8

Mukesh Shakya
  • 319
  • 3
  • 7
  • All except the first use external processes, which generally you want to avoid whenever you can. The alternatives might be useful for `sh` scripts (see also [Difference between sh and bash](https://stackoverflow.com/questions/5725296/difference-between-sh-and-bash)). – tripleee Oct 02 '21 at 08:54
-2

Try something like this:

echo "Str is: `expr length $Str` characters long"
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 2
    Can you explain why you believe this answers the OP's question? Have _you_ tried both ways and compared the results? – GoojajiGreg Nov 24 '18 at 02:17
  • The downvotes and the preceding comment are probably (at least partially) due to Markdown formatting errors which originally wrecked this answer. Still, probably prefer modern `$(command substitution)` syntax over the legacy backticks from the early 1990s, and maybe actually don't recommend `expr`. Oh, and [absolutely quote the string variable.](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) Anyway, this isn't really an improvement over the OP's code. – tripleee Oct 02 '21 at 08:53