27

I've to verify the length of variable read (my script limit to five the characters inserted), I think about something like this:

#!/bin/bash
read string
check=${#string}
echo $check
if [ $check -ge 5 ]; then echo "error" ; exit
else echo "done"
fi

is there a more "elegant" solution?

  • 1
    Your script works correctly in standard POSIX /bin/sh. You should consider changing the shebang line to #!/bin/sh so that it will be more portable and run in environments where bash isn't available. Plus, /bin/sh might be a more lightweight shell like dash which isn't burdened with features meant for interactive use. – Celada Jul 17 '14 at 22:15
  • @Celada, true though in this case, dash's ${#string} would give you the length in number of bytes instead of characters. – Stéphane Chazelas Apr 20 '17 at 16:28
43

More elegant? No

Shorter? Yes :)

#!/bin/bash
read string
if [ ${#string} -ge 5 ]; then echo "error" ; exit
else echo "done"
fi

And if you have no problem on trading more elegance in favor of being shorter, you can have a script with 2 lines less:

#!/bin/bash
read string
[ ${#string} -ge 5 ] && echo "error" || echo "done"

You could use double brackets if you think it is safer. Explanation here.

3

A Bourne-compatible alternative (${#string} is POSIX but not Bourne (not that you're likely to ever come across a Bourne shell these days)):

case $string in
  ?????*) echo >&2 Too long; exit 1;;
       *) echo OK
esac

Note that for both ${#string} and ????, whether it will be the number of bytes or characters will depend on the shell. Generally (and it's required by POSIX), it is the number of characters. But for some shells like dash that are not multi-byte aware, it will be bytes instead.

With mksh, you need set -o utf8-mode (in UTF-8 locales) for it to understand multi-byte characters:

$ string=€€€ bash -c 'echo "${#string}"'
3
$ string=€€€ dash -c 'echo "${#string}"'
9
$ string=€€€ mksh -c 'echo "${#string}"'
9
$ string=€€€ mksh -o utf8-mode -c 'echo "${#string}"'
3
$ locale charmap
UTF-8
  • off topic, but is echo Too long different under the hood from echo 'Too long' – Steven Penny Apr 20 '17 at 16:38
  • And, if you will just print when it's "too long", i can compact even more on my if option :) – user34720 Apr 20 '17 at 16:40
  • 1
    @StevenPenny, echo Too long passes two arguments (Too and long) to echo which echo outputs separated by a space (and followed by a newline), while in echo 'Too long', we pass one Too long argument to echo which it displays following by a newline. So it's functionnaly equivalent. – Stéphane Chazelas Apr 20 '17 at 16:40

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.