4

I have a FreeBSD 9.3 RELEASE server and I am trying to write a shell script using sh. I am trying to get the length of a variable that is passed to a function in a shell script, like so:

#!/bin/sh

myfunc() {
  varlength=${#1}
  echo $varlength
}

test="aaaaa aaaaa"
myfunc $test

The above script should return 11, which is the length of the test variable, but ${#1} does not seem to work. I have also tried many other ways to accomplish that but i can't figure it out.

varlength=$(expr ${#1})  does not work
varlength=$(${#1})  does not work
varlength=$(expr \( "X$1" : ".*" \) - 1)  does not work
varlength=$({#1})  does not work

and many many other attempts I made failed.

  • Can you try declaring the script as bash in the she-bang? Like this: #!/usr/bin/env bash – ryekayo Sep 30 '14 at 20:37
  • 1
    Instead of trying to do it with a shell built-in, you could always echo it and pipe it to the "wc -c" program to count the characters. Slightly more expensive of course. – BobDoolittle Sep 30 '14 at 20:37
  • 1
    ${#1} is defined in posix. I don't know what shell you're using, but it should work. What is happening when you run it? Error, no output, what? The result I expect is 5. – Patrick Sep 30 '14 at 20:43
  • The script is rather long and declaring it as bash would mean that I have to spend some time making sure it works, since it is written with sh in mind. Piping it to wc would require that I export the variable to a file and passing that file as an argument to wc which is indeed more expensive. ${#1} is indeed defined in POSIX. The result I get is also 5, but as you can see it is wrong. The actual length of the variable is 11. After 11 hours scripting, I might be missing something that is obvious to someone else, that is why I asked here. Thank you for your replies. – Zerotronic Zerotronicus Sep 30 '14 at 21:17
  • No, piping to wc does not require writing the variable to a file; just do varlength=$(echo "$1" | wc -c). (You'll want to subtract 1 from the result, because it will count the newline. Or, do echo -n "$1" or echo -e "$1\c" -- but not if $1 might contain backslashes.) – G-Man Oct 1 '14 at 21:51
8

because $test contains whitespace, when you say

myfunc $test # without quotes

your function receives > 1 argument. myfunc receives 2 arguments here, aaaaa and aaaaa.

You want this:

myfunc "$test" # with quotes

Rule of thumb: always quote your "$variables" unless you know exactly when and why not to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.