[Top][All Lists]

[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: Greg Wooledge
Subject: Re: How to make `read` fail if there is not enough fields in the input?
Date: Thu, 5 Dec 2019 08:44:05 -0500
User-agent: Mutt/1.10.1 (2018-07-13)

> On 12/4/19 10:19 PM, Peng Yu wrote:
> >> $ IFS=$'\t' read -r -a array <<< x && (( "${#array[@]}" == 2 ))

The fundamental problem here is that tab is a whitespace character.
When you use whitespace characters in IFS to delimit fields, multiple
consecutive instances of IFS whitespace characters are considered ONE

In other words:

wooledg:~$ IFS=$'\t' read -ra array <<< $'foo\t\t\tbar\tbaz\t'
wooledg:~$ declare -p array
declare -a array=([0]="foo" [1]="bar" [2]="baz")

The "solution" to this, if you can call it that, is to use something
other than whitespace as your delimiter.  You could, for example,
replace all of the tab characters with $'\003' characters, and then
use $'\003' as your delimiter.

You might want to avoid using $'\001' and $'\002' as delimiters,
because bash uses those internally in some places, and there have been
a multitude of shell bugs involving them.  Mostly fixed in 5.0, perhaps,
but I'm sure there are some more bugs lurking.

Also, stop being an asshole.  I'm probably not going to un-killfile
you any time soon, but I already see you pissing off Eli Schwartz, and I
doubt you want to lose any more of your dwindling number of helpers.
Demanding that solutions be "short", when the language is incapable of
doing so, just comes across as entitled, spoiled, selfish, arrogant....

Bash is what it is.

reply via email to

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