What exactly does the following do?
MY_VAR=${MY_INPUT##*$'\n'}
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityDeletes the longest match of the substring *\n
from the start of the string stored in MY_INPUT
. Note that *
is a wildcard, so the result is that every line of MY_INPUT
is discarded except the last one, which is stored in MY_VAR
. The $
before '\n'
is put there just to evaluate \n
and consider it as a newline instead of literally the characters \
and n
.
Some examples:
MY_INPUT MY_VAR
"a\nb\nc" -> "c"
"a\n" -> ""
"abcde\n\n\ndef" -> "def"
Note: in the second example the last line is empty so MY_VAR
is an empty string.
As requested, another way to do this could be:
tail -n1 <<< "$MY_INPUT"
or:
echo "$MY_INPUT" | tail -n1
MY_INPUT=$( printf 'line1\nline2\nline3' ); MY_VAR=${MY_INPUT##*$'\n'}; echo "$MY_VAR"
will output line3
. It's basically doing tail -n 1
on the contents of $MY_INPUT
.
– Kusalananda♦
Mar 21 '18 at 11:52