Handling null Integer/string variables

I kind of found out the hard way that I am not able to manipulate the null value, the long silence that happens when there is no value returned.
I am looking for PIDs, and when there is no PID return, I wanted to handle this special scenario.

Here is my script.

#!/bin/bash
LAN_VARIABLE= echo `ps -ef | grep mintty | awk '{print $2}'`
echo $LAN_VARIABLE
if [[ $LAN_VARIABLE =~ ^[0-9]+$ ]]; then
        echo "An Integer"
else
        echo "not an integer"
fi

When there is no mintty process running, i wanted the else loop to be printed and when there is a pid , then the if part to be printed. But it always prints "not an integer", even though the echo $LAN_VARIABLE returns PID.

A much easier way, and a way that can be handled in any shell not just BASH, is to use -z to check for blank variables.

if [ -z "$VARIABLE" ]
then
...
else
...
fi
1 Like

The reason it always finds a PID is because it's finding the grep.

I don't have "bash" hand to try a fix but the "echo" is not needed or desirable (it introduces an extra line terminator which could be upsetting your numeric comparison). Also the script will misbehave if there is more than one line in "ps -ef" which contains the string "mintty" .

My guess for the first fix (untested):

LAN_VARIABLE=$(ps -ef | grep mintty | grep -v grep |awk '{print $2}')
1 Like

Also eliminate the grep -v grep and save a process by doing this:

LAN_VARIABLE=$(ps -ef | grep "[m]intty" | awk '{print $2}')

Matches the string "mintty" but not itself, thus eliminating the need to grep -v grep..

1 Like

[m]intty is both a valid regular expression for grep and a valid sh pattern for pathname expansion. If you don't quote that argument, and if the current working directory has a matching item, the pathname expansion would consume the brackets before grep is exec'd. The pipeline could give an erroneous result if its grep is listed in ps' output.

Obviously, what I just pointed out is not likely to happen, but it's not impossible. I mention it merely for thoroughness.

Regards,
Alister

2 Likes

Excellent point, thanks. I corrected my example above for future searchers.

1 Like

Hi guys, thanks a lot for so many replies....

It was good solution to use

ps -ef | grep "[m]intty" | awk '{print $2}'

This works and gives only one PID. The actual problem I found out was that, the variable never gets a value assigned. The PID value getting printed was from the following step.

LAN_VARIABLE= echo `ps -ef | grep "[m]intty" | awk '{print $2}'`

echo $LAN_VARIABLE always returned null, hence the if loop had the ambiguity.

I used the following and it worked.

if [-z `ps -ef | grep [m]intty | awk '{print $2}'`]; then
echo "not an Integer"
else
echo "An Integer"
fi

Don't forgot to put double-quotes around the [m]intty and spaces just after/before the square brackets:

if [ -z `ps -ef | grep "[m]intty" | awk '{print $2}'` ]; then