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

might not be most efficient but one liner...

firstLine=`echo "${multiLineVariable}" | head -1`

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]}"

That code works for me with all versions of bash I tried between 2.05b and 4.3. More likely you tried to run that script with a different shell that doesn't support the $'...' form of quoting.

That $'...' syntax is not standard sh syntax (yet) and only supported (as of 2015-05-22 and AFAIK) by ksh93 (where it originated), zsh, bash, recent versions of mksh and the sh or recent versions of FreeBSD.

My bet would be that you tried to run that script with sh instead of bash and your sh is based on versions of ash, pdksh, yash or ksh88 that don't support it yet.

If you want to make that code POSIX 2008 compatible, you'd need to write it:

STRINGTEST="Onlygetthefirstline
butnotthesecond
orthethird"

NL='
'
STRINGTEST=${STRINGTEST%%"$NL"*}
printf '%s\n' "$STRINGTEST"

Then, you can have it interpreted by any POSIX compliant shell like bash or any leaner/faster ones like your sh.

(and remember that leaving a variable unquoted in list context has a very special meaning in Bourne-like shells).

Tags:

Bash