Question

I'm sort of a newbie when it comes to shell scripting. What am I doing wrong?

I'm trying to grep a running log file and take action if the grep returns data.

# grep for "success" in the log which will tell us if we were successful
tail -f file.log | grep success > named_pipe &

# send signal to my server to do something
/bin/kill -10 $PID

timeout=0;
while : ; do
    OUTPUT=$(cat < named_pipe)
    if test [-n] $OUTPUT
        then
            echo "output is '" $OUTPUT "'"
            echo_success
        break;
    else
        timeout=$((timeout+1))
        sleep 1 
        if [ $timeout -ge $SHUTDOWN_TIMEOUT ]; then
            echo_failure
            break
        fi
    fi
done

I'm finding that even when "success" is not in the log, test [-n] $OUTPUT returns true. This is because apparently OUTPUT is equal to " ". Why is OUTPUT a single space rather than empty?

How can I fix this?

Was it helpful?

Solution

Here's a smaller test case for your problem:

output=""
if test [-n] $output
then
  echo "Why does this happen?"
fi

This happens because when $output is empty or whitespace, it expands to nothing, and you just run test [-n].

test foo is true when foo is non-empty. It doesn't matter that your foo is a flag wrapped in square brackets.

The correct way to do this is without the brackets, and with quotes:

if test -n "$output"
then
  ...
fi

As for why $OUTPUT is a single space, that's simple: it isn't. echo just writes out its arguments separated as spaces, and you specified multiple arguments. The correct code is echo "output is '$OUTPUT'"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top