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..

3
  • 1
    Strongly related: unix.stackexchange.com/questions/65803/… Commented Mar 21, 2018 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} Commented Mar 21, 2018 at 19:23
  • methinks /user/ilkkachu has OCD. :) Commented Mar 23, 2018 at 8:33

1 Answer 1

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}"
2
  • Why then does this have the same problem? > test="-efoo"; answer=${test:0:2}; echo $answer Commented Mar 21, 2018 at 19:20
  • 1
    You’re still passing -e to echo... Commented Mar 21, 2018 at 19:28

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.