Search code examples
ksh

KSH | `-n` option inside an if statement


I was checking a korn shell script and I stumbled upon this:

if [[ -n `echo "This is an example." | grep -E "example"` ]]; then
  # Do something.
fi

Can someone tell me what the -n is doing?


Solution

  • Suggesting to check this article:

     [[ -n "string" ]] true if length of string is greater than zero
    

    Similar to

    if [[ `echo "This is an example." | grep -Ec "example"` -gt 0 ]]; then
      # Do something.
    fi
    

    Also better practice for if statements:

    if [[ -n $(echo "This is an example." | grep -E "example") ]]; then
      # Do something.
    fi