NUL delimited variable
It is a fact that you can't store \0
null bytes in a bash string context, because of the underlying C implementation. See Why $'\0' or $'\x0' is an empty string? Should be the null-character, isn't it?.
One option would be strip off the null bytes after the sort command, at the end of the pipeline using tr
and store the result to solve the immediate problem of the warning message thrown. But that would still leave your logic flawed as the filenames with newlines would still be broken.
Use an array, use the mapfile
or readarray
command (on bash 4.4+) to directly slurp in the results from the find
command
IFS= readarray -t -d '' samples < <(find . -type d -iregex './sample[0-9][0-9]' -printf "%f\0" | sort -z)
The bash
shell does not support what you want to do. The zsh
shell does out of the box.
% mkdir sample11 SAMple12 sample21 sample22 dir1
% ll
total 20
drwxrwxr-x 2 fpm fpm 4096 Jun 9 13:46 dir1
drwxrwxr-x 2 fpm fpm 4096 Jun 9 13:46 sample11
drwxrwxr-x 2 fpm fpm 4096 Jun 9 13:46 SAMple12
drwxrwxr-x 2 fpm fpm 4096 Jun 9 13:46 sample21
drwxrwxr-x 2 fpm fpm 4096 Jun 9 13:46 sample22
% samples=$(find . -type d -iregex './sample[0-9][0-9]' -print0 | sort -z)
% echo $samples
./sample11./SAMple12./sample21./sample22
% echo $samples | od -a
0000000 . / s a m p l e 1 1 nul . / S A M
0000020 p l e 1 2 nul . / s a m p l e 2 1
0000040 nul . / s a m p l e 2 2 nul nl
0000055
%