What exactly does the following do?


Deletes 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"


echo "$MY_INPUT" | tail -n1
  • Could you give an example of input/output? – Jim Mar 21 '18 at 11:22
  • @Jim 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
  • @Jim Added some examples! – Marco Bonelli Mar 21 '18 at 12:58
  • Is there a more readable way to accomplish the same thing? – Jim Mar 21 '18 at 18:15
  • @Jim added this too! – Marco Bonelli Mar 21 '18 at 18:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.