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
You can split strings in bash using the Internal Field Separator (IFS) and read command or you can use the tr command.
To just print the null character, use printf '\0' .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With