Trying to retrieve first 5 characters from string in bash error?

I'm trying to retrieve the first 5 characters from a string and but keep getting a Bad substitution error for the string manipulation line, I have the following lines in my teststring.sh script:

TESTSTRINGONE="MOTEST"

NEWTESTSTRING=${TESTSTRINGONE:0:5}
echo ${NEWTESTSTRING}

I have went over the syntax many times and cant see what im doing wrong

Thanks


Solution 1:

Depending on your shell, you may be able to use the following syntax:

expr substr $string $position $length

So for your example:

TESTSTRINGONE="MOTEST"
echo `expr substr ${TESTSTRINGONE} 0 5`

Alternatively,

echo 'MOTEST' | cut -c1-5

or

echo 'MOTEST' | awk '{print substr($0,0,5)}'

Solution 2:

echo 'mystring' |cut -c1-5 is an alternative solution to ur problem.

more on unix cut program

Solution 3:

Works here:

$ TESTSTRINGONE="MOTEST"
$ NEWTESTSTRING=${TESTSTRINGONE:0:5}
$ echo ${NEWTESTSTRING}
MOTES

What shell are you using?

Solution 4:

Substrings with ${variablename:0:5} are a bash feature, not available in basic shells. Are you sure you're running this under bash? Check the shebang line (at the beginning of the script), and make sure it's #!/bin/bash, not #!/bin/sh. And make sure you don't run it with the sh command (i.e. sh scriptname), since that overrides the shebang.

Solution 5:

This might work for you:

 printf "%.5s" $TESTSTRINGONE