Search code examples
bashstring-length

How to get correct length of string in motd?


I'm new to bash script. I made my original motd script on my server machine(ubuntu 20.04). In that script, I'm trying to get a length of string. It works correctly on server machine. However it displayed wrong number, when I connected to server machine from laptop(OSX 11.1 and ubuntu 20.04) by using ssh. Could you tell me why it is happening?

</etc/update-motd.d/my-motd>

#!/bin/bash
line1="██╗"
printf "${#line1}"

It will return 9 but it should 3... Also, this problem only happens at ssh login.

Best,


Solution

  • In your example, there is a Unicode character. According to POSIX, shell should have Unicode support, but it must be switched on with a proper variable(s).

    Therefore either the machine you call "laptop" or the account you connect to is not configured to have a locale with utf-8 support. Try to set at least LC_CTYPE=UTF-8 but setting to your proper locale (and maybe even LANG or LC_ALL) variables would be even better.

    For details on so called internatinalisation variables, please see: https://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html (TL;DR: LANG makes a default for unset vars, LC_ allows some granularity, LC_ALL is the boss.)