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:33:42 -0500
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.2.2

On 12/4/19 10:19 PM, Peng Yu wrote:
>> $ IFS=$'\t' read -r -a array <<< x && (( "${#array[@]}" == 2 ))
>> $ echo $?
>> 1
>> $ IFS=$'\t' read -r -a array <<< x$'\t'y && (( "${#array[@]}" == 2 ))
>> $ echo $?
>> 0
> 
> But this is too verbose. I also want to directly refer to x and y
> rather than the array. Anything as succinct as the original bash
> code?

Aside for it not handling lines where the last field is empty (and a
million other edge cases when parsing the CSV file format), what is
wrong with "verbose"?

The original bash code doesn't work, so it doesn't matter how verbose it is.

If you're asking "does bash currently have the feature I have asked
for", the answer is "no", so you need to either stop asking for "as
succinct as the thing which doesn't work" and settle for a solution that
hopefully produces the correct result (regardless of verbosity), or...
you need to ask Chet to add a new language feature for your use case.

Alternatively, you could use an external utility that knows how to parse
CSV or TSV files, and if you're feeling in a particularly industrious
mood I suppose you could write your own utility that implements a bash
loadable builtin which can be used in-process and therefore set
variables directly.

-- 
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]