Parsing null or empty output

I am working an some if then statements for a script.

I want to be able to check for alpha characters or empty out put then exit out.

if [[ $lastseen = [A-Z] ]]; 
echo "Serial Number Invaild"
then exit 3; 

How do I account if the output is empty or null in this in this statement.

Many thanks

In bash, for regular expression matching, you have to use a =~ regular expression matching operator

For checking if string is empty, you can use a -z string test operator

So you can try:-

if [[ "$lastseen" =~ '^[a-ZA-Z]*$' ]] && [ ! -z "$lastseen" ]
then
        echo "Serial Number Valid"
else
        echo "Serial Number Invaild"
        exit 3
fi

With a shell glob you need two conditions

if [[ -z $lastseen ]] || [[ $lastseen == *[_a-zA-Z]* ]]
then
  echo "empty or has an alpha character"
fi
if [[ -z $lastseen ]] || [[ $lastseen == *[!0-9]* ]]
then
  echo "empty or has a non-digit character"
fi

If the requirement is that only digits may occur, you can test for the negation of a string of 1 or more digits instead:

if ! [[ $lastseen =~ ^[0-9]+$ ]]; then
  echo "Serial Number is invalid: it does not consist entirely of digits"
  exit 3
fi

With regular patterns you could use:

case $lastseen in 
  (*[!0-9]*|"") 
    echo "Serial Number Invalid: it does not consist entirely of digits"
    exit 3
  ;;
esac

---

You can use one condition like so:

if [[ -z $lastseen || $lastseen == *[_a-zA-Z]* ]]; then

---

To use regexes you need to leave them unquoted. But even without the quotes, this would seem to do the opposite of what is required. The left condition tests whether a string consists exclusively of alpha characters (letters) or is empty, whereas the requirement is that no non-digits may occur.

1 Like
if [[ ${lastseen:-a} =~ [^0-9] ]]
then 
   echo "Serial number invalid"
   exit 3
fi

If lastseen is null or unset replace with an invalid string sequence. In this case the letter a will suffice.

Andrew

Hi andysensible...

An additional note to Scrutinzer's post...

This is the only reply, in the few that have been posted, that is fully POSIX compliant and will work in 'sh' and 'dash' too, thus making it basically portable...

I call this a trick.
Nice somehow, but I am not going to recommend that as a common practice...