help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to make `read` fail if there is not enough fields in the input?


From: Eli Schwartz
Subject: Re: How to make `read` fail if there is not enough fields in the input?
Date: Wed, 4 Dec 2019 22:01:01 -0500
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.2.2

On 12/4/19 9:12 PM, Peng Yu wrote:
> I’d like to know whether there is enough field in a TSV row.

Are you building a TSV validator in bash? o_O

What damage can happen if the TSV file does not have enough fields and
bash treats those as empty fields?

> But the status code does not return an error code. Is there a way to
> let read return non-zero if there is not enough fields? Thanks.
> 
> $ IFS=$'\t' read -r x y <<< x
> $ echo $?
> 0

Why do you require to use the "error code" technology, specifically?
What is wrong with checking the length of your produced variables?

You could use mapfile and simply count the number of results:

$ mapfile -t -d $'\t' arr < <(printf $'x\t\t\t')

This "correctly" detects 3 elements, two of which are empty.

Note this will do the wrong thing for input ending in a newline; the
newline gets treated as the last portion of the last element of ${arr[@]}

It also ignores the last element, if it is empty, so you should make
sure to not only remove a trailing newline (using <<< will result in a
trailing newline, < <(printf ...) won't), but add a trailing tab too, to
thus adding a final empty field for mapfile to drop.

-- 
Eli Schwartz
Arch Linux Bug Wrangler and Trusted User

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]