What does cut return if the specified field does not exist?

To answer your direct question, cut returns nothing except a trailing newline, as per the spec (thanks to don_crissti for that reference):

echo "$versionfull" | cut -d. -f3 | od -c
0000000  \n
0000001

If you have a shell that supports here-strings, you could do the following:

IFS=. read a b c <<< "$versionfull"

Notice the quoting for $versionfull, in case it ever had whitespace (anything from $IFS).

If you think that c might be empty, then ask to set it to zero:

c=${c:-0}

You could use var=$(echo "${versionfull}.0" | cut -d'.' -f3).

In the first case, versionfull will contain 6.40.4.0, ignoring the padding and returning 4 as needed. In the second case, the .0 will be padded and returned.


cut has an odd API.

cut -f n will output the nth field of each line that has at least one delimiter (empty if the line has fewer than n-1 delimiters (fewer than n fields)), and returns the full line (so the first field) for those that don't have any delimiter:

$ echo a.b.c | cut -d. -f3
c
$ echo a.b | cut -d. -f3

$ echo a | cut -d. -f3
a

So the answer to What does cut return if the specified field does not exist? is either the first field or an empty field depending on whether the input line has one field or more.

You can add the -s option to remove the lines that don't have any delimiter to avoid that weird last case above, but that's generally not what you want (you'd generally want to consider that input line to have an empty 3rd field instead of skipping it altogether), and that's worth if you want the first field:

$ echo a | cut -sd. -f2
$ echo a | cut -sd. -f1
$

(you asked for the first field, the input has only one field, but you don't get any output because the input has no delimiter).

So @ThoriumBR's suggestion to add a .0 is a very good one. Without it:

versionfull=5
echo "$versionfull" | cut -d. -f3

would actually output 5. By adding .0, we make sure the input has at least one delimiter. I would go further and use:

echo "$versionfull.0.0" | cut -d. -f3

To make sure the input has at least 3 fields.