Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash syntax help - mapfile/readarray (split text into array) [closed]

Tags:

syntax

bash

In bash, in some StackOverflow answers they show how to populate the results to find files into an array:

Info 1

Older bash versions

mapfile -d $'\0' array < <(find . -name "${input}" -print0)

OR newer bash versions: (4.2+)

readarray -d '' array < <(find . -name "$input" -print0)

Info 2

Then there is also this to split a string into an array but this doesn't work for me.

readarray -d '|' PORTS <<< "${matched}"

I use this successfully, but this is older syntax.

IFS='|' read -r -a PORTS <<< $matched

Those answers do not explain the full syntax though:

Can someone please explain:

Info 1:

What is the the < bracket just before the normal ( bracket doing? If I add a space and/or replace that with a $ then the command fails. But I would like to understand what that is doing.

Info 2:

Somewhere I found this syntax for readarray, but it doesn't work for me, so it could be the same issue with the bracket < placements. How to use it correctly?

like image 312
CvRChameleon Avatar asked Feb 22 '26 15:02

CvRChameleon


1 Answers

I have not received an answer which I would have upvoted. To answer the question for Info 1, in case the link ever expires that Nahuel gave, the relevant part. This is important for me because sometimes I would like to understand what a given solution does, and sometimes that part is not explained in answers.

Its called Process Substitution

Process Substitution

Process substitution allows a process’s input or output to be referred to using a filename. It takes the form of

<(list)

or

>(list)

Functionality

The process list is run asynchronously, and its input or output appears as a filename. This filename is passed as an argument to the current command as the result of the expansion.

  • If the >(list) form is used, writing to the file will provide input for list.
  • If the <(list) form is used, the file passed as an argument should be read to obtain the output of list.

Regarding my question about spaces

Note that no space may appear between the < or > and the left parenthesis, otherwise the construct would be interpreted as a redirection. Process substitution is supported on systems that support named pipes (FIFOs) or the /dev/fd method of naming open files.

When available, process substitution is performed simultaneously with parameter and variable expansion, command substitution, and arithmetic expansion.

I still need clarification on Info 2 though.

like image 75
CvRChameleon Avatar answered Feb 24 '26 14:02

CvRChameleon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!