1

How do I check the variable $last_cmd has new lines only and nothing else in Zsh?

Ideally done via substitution, as this is part of a prompt script, so needs to be really fast.

The following gives me a bad substitution error:

if [[ -n "${$last_cmd/\n/}" ]]; then
  no_new_lines=1
fi

Basically want the equivalent of the following:

if [[ -n "$(echo -n $last_cmd)" ]]; then
  no_new_lines=1
fi
  • 1
    Your syntax is broken (it should be ${var/pat/rpl} not ${$var/pat/rpl}, you should use // instead of / to replace all matches, and \n will match just n not newline. – mosvy Mar 5 at 11:40
1

With a regex:

if [[ $1 =~ ^$'\n'*$ ]]; then
  echo empty or only contains newlines
else
  echo contains non-newline characters 
fi

With wildcards, instead of directly testing that there are only newlines, test for the presence of a non-newline character:

if [[ $1 == *[^$'\n']* ]]; then
  echo contains non-newline characters 
else
  echo empty or only contains newlines
fi

Or the plain sh way:

nl='
'
case $1 in
  *[!$nl]*) echo contains non-newline characters;;
  *) echo only contains newlines;;
esac

For a positive match with wildcards, you'd need the # extendedglob operator (the equivalent of the * regexp operator):

set -o extendedglob
if [[ $1 == $'\n'# ]]; then
  echo empty or only contains newlines
else
  echo contains non-newline characters 
fi
| improve this answer | |
  • So, an empty string only contains newlines? – mosvy Mar 5 at 11:40
  • @mosvy Yes, sure. – Gilles 'SO- stop being evil' Mar 5 at 11:41
  • h‎o‎w c‎o‎m‎e?‎ – mosvy Mar 5 at 11:45
  • @mosvy Does a sidewalk stop being for pedestrians only when nobody is walking on it? – Gilles 'SO- stop being evil' Mar 5 at 11:47
  • That's a way to look at it. So "Jen is only wearing pink underwear" is the same as "Jen is never wearing any underwear". For the sake of clarity, I would avoid playing with vacuous statements. – mosvy Mar 5 at 11:58

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.