help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Readig multiple null-separated values


From: Greg Wooledge
Subject: Re: [Help-bash] Readig multiple null-separated values
Date: Mon, 29 Jul 2019 09:07:43 -0400
User-agent: Mutt/1.10.1 (2018-07-13)

On Mon, Jul 29, 2019 at 09:50:21PM +0900, Koichi Murase wrote:
> > My question is:
> >
> > 1) Is there a simpler solution than my read_nullbyte() function?
> >
> > 2) Do you consider it generic and useful enough to make it built-in part
> > of GNU Bash?
> >
> > Franta
> 
> In Bash 4.4, the builtin `mapfile' has an opton `-d delim' which
> enables to change the delimiter from newlines. It accepts an empty
> string which actually behaves as NUL separator. For example, the
> provided example can be written with `mapfile' as follows:
> 
>   $ printf 'a\0aaa\0b\0bbb\0c\0ccc' | { mapfile -d '' arr; declare -p arr; }
>   declare -a arr=([0]="a" [1]="aaa" [2]="b" [3]="bbb" [4]="c" [5]="ccc")

And prior to bash 4.4, the only choice was IFS= read -r -d '' which works
basically the same way, just with string variables instead of array
variables.

$ for var in a b c; do IFS= read -r -d '' "$var"; done < <(printf 
'a\0aaa\0b\0bbb\0c\0ccc\0')
$ declare -p a b c
declare -- a="a"
declare -- b="aaa"
declare -- c="b"

Since the OP seems to be asking for a Swiss Army Knife that handles either
arrays or strings (and opens wine bottles too), the only answer we can
give is: there is no single tool.  What you use depends on the situation.

 * If you need a fixed number of string values, you can simply call
   read however many times you require.

 * If you need an array, and you're in bash 4.4 or newer, you can use
   mapfile.

 * If you need an array, and you're targeting older bash releases, you
   can call read inside a while loop, and build up the array that way.



reply via email to

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