I'm reading the last line of a file into a variable. Then I want to get the last X characters of the string variable:
#!/bin/bash
someline="this is the last line content"
echo ${someline}
somepart=${someline: -5}
echo ${somepart}
Run with: sh lastchars.sh
Result:
this is the last line content
line 4: Bad substitution
What might be wrong here?
It sounds like you're not using
bash
at all. I can only reproduce the error you show if I usedash
instead ofbash
:bash
:dash
:Your shebang line is pointing to
bash
, but you are running the script withsh
, so the shebang is ignored./bin/sh
on Ubuntu systems is actuallydash
, a minimal shell that doesn't support the syntax you are trying to use.When using a shebang line, there's no reason to explicitly call a shell for the script, just make it executable (
chmod a+x /path/to/script.sh
) and run it without specifying an interpreter:Alternatively, just use the right one:
Obviously using the build-in functions of a certain shell are nice, but you can also accomplish the task using standard UNIX commands, so it will work in any shell: