1

On Linux Mint, using bash..

test="-ffoo"; echo ${test:0:2}

works outputting the first two characters

but

test="-efoo"; echo ${test:0:2}

fails, with apparently null output.

I'm thinking the form of this is

${parameter:offset:length}

I know enough that parameter characters cannot be *@#?-$!0_

but $test is the parameter - surely its contents can be anything? I guess -e is triggering something shell-like but why..

ilkkachu
  • 138,973
  • 1
    Strongly related: https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo – Jeff Schaller Mar 21 '18 at 18:42
  • This is more about getting the correct answer than the diff between echo and printf. [test="-efoo"; answer=${test:0:2}; echo $answer ] seems to have the same problem with answer not seeing the correct result from ${test:0:2} – David Brown Mar 21 '18 at 19:23
  • methinks /user/ilkkachu has OCD. :) – David Brown Mar 23 '18 at 08:33

1 Answers1

3

When you run

test="-efoo"; echo ${test:0:2}

echo is run with the argument -e, which in some echo implementations including the echo builtin command of most bash deployments, is a valid option and is thus “swallowed”.

Use printf instead:

test="-efoo"; printf %s\\n "${test:0:2}"
Stephen Kitt
  • 434,908