Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pipe a null separated string into an array in bash?

Tags:

bash

Given a command that outputs multiple strings separated by bytes, whats the best (fastest) way to convert this into an array in bash.

eg: git ls-files -z

like image 899
ideasman42 Avatar asked Jan 10 '19 11:01

ideasman42


People also ask

How do you split a string into an array in Unix?

You can split strings in bash using the Internal Field Separator (IFS) and read command or you can use the tr command.

How do I echo null characters?

To just print the null character, use printf '\0' .

How do I split a string in bash?

In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.


1 Answers

For bash 4.4 and later only:

readarray -d '' array < <(git ls-files -z)

For backwards compatibility with bash 3.x and 4.0 through 4.3:

array=( )
while IFS= read -r -d '' item; do
  array+=( "$item" )
done < <(git ls-files -z)
like image 193
Charles Duffy Avatar answered Nov 14 '22 16:11

Charles Duffy