Bash get last line from a variable Bash get last line from a variable bash bash

Bash get last line from a variable


An easy way to do this is to use tail:

echo "$STRING" | tail -n1


Using bash string manipulations:

$> str="This is amultiple linevariable test"$> echo "${str##*$'\n'}"variable test

${str##*$'\n'} will remove the longest match till \n from start of the string thus leaving only the last line in input.


If you want an array with one element per line from STRING, use

readarray -t lines <<< "$STRING"

Then, the first line would be ${lines[0]}, and the last line would be ${lines[-1]}. In older versions of bash, negative indices aren't allowed and you'll have to compute the last index manually: ${lines[${#lines[@]}-1]}.