Bash: Assigning the first line of a variable to a variable

bash

I have a multiline variable, and I only want the first line in that variable. The following script demonstrates the issue:

#!/bin/bash

STRINGTEST="Onlygetthefirstline
butnotthesecond
orthethird"

echo "  Take the first line and send to standard output:"
echo ${STRINGTEST%%$'\n'*}
#   Output is as follows:
# Onlygetthefirstline

echo "  Set the value of the variable to the first line of the variable:"
STRINGTEST=${STRINGTEST%%$'\n'*}

echo "  Send the modified variable to standard output:"
echo $STRINGTEST
#   Output is as follows:
# Onlygetthefirstline butnotthesecond orthethird

Question: Why does ${STRINGTEST%%$'\n'*} return the first line when placed after an echo command, but replace newlines with spaces when placed after assignment?

Best Answer

Maybe there is other way to archive what you want to do, but this works

#!/bin/bash

STRINGTEST="
Onlygetthefirstline
butnotthesecond
orthethird
"

STRINGTEST=(${STRINGTEST[@]})
echo "${STRINGTEST[0]}"
Related Question