Let's suppose that we have the following contents in current directory:
$ ls -la
total 52
drwxr-xr-x 3 dmitritelinov dmitritelinov 4096 Sep 21 20:59 .
drwxr-xr-x 9 dmitritelinov dmitritelinov 4096 Sep 16 19:47 ..
-rw-r--r-- 1 dmitritelinov dmitritelinov 219 Sep 21 20:59 array.sh
-rw-r--r-- 1 dmitritelinov dmitritelinov 266 Aug 29 22:07 datasources.tf
-rw-r--r-- 1 dmitritelinov dmitritelinov 16 Sep 12 22:40 dev.tfvars
-rw-r--r-- 1 dmitritelinov dmitritelinov 119 Sep 4 22:51 linux-ssh-config.tpl
-rw-r--r-- 1 dmitritelinov dmitritelinov 2555 Sep 16 21:25 main.tf
-rw-r--r-- 1 dmitritelinov dmitritelinov 62 Sep 18 23:20 outputs.tf
drwxr-xr-x 3 dmitritelinov dmitritelinov 4096 Apr 25 21:37 .terraform
-rw-r--r-- 1 dmitritelinov dmitritelinov 1106 Apr 16 22:55 .terraform.lock.hcl
-rw-r--r-- 1 dmitritelinov dmitritelinov 18 Sep 10 22:24 terraform.tfvars
-rw-r--r-- 1 dmitritelinov dmitritelinov 460 Aug 31 23:25 userdata.tpl
-rw-r--r-- 1 dmitritelinov dmitritelinov 61 Sep 10 22:24 variables.tf
And if we run the below command - we are getting a null delimited string:
$ find -maxdepth 1 -type f -name "*.tf" -print0
./outputs.tf./datasources.tf./main.tf./variables.tf
The output of this command will have \0 character - non printable character:
$ find -maxdepth 1 -type f -name "*.tf" -print0 | cat -v
./outputs.tf^@./datasources.tf^@./main.tf^@./variables.tf^@
^@ means the ASCII character control-@, i.e. character 0, which in C is the string end character.$ find -maxdepth 1 -type f -name "*.tf" -print0 | hd
00000000 2e 2f 6f 75 74 70 75 74 73 2e 74 66 00 2e 2f 64 |./outputs.tf../d|
00000010 61 74 61 73 6f 75 72 63 65 73 2e 74 66 00 2e 2f |atasources.tf../|
00000020 6d 61 69 6e 2e 74 66 00 2e 2f 76 61 72 69 61 62 |main.tf../variab|
00000030 6c 65 73 2e 74 66 00 |les.tf.|
To parse such string in bash, there is a following example - array.sh:
$ cat array.sh
#!/bin/bash
array=()
while IFS= read -r -d $'\0'; do
array+=("$REPLY")
done < <(find -maxdepth 1 -type f -name "*.tf" -print0)
for i in "${array[@]}"
do
echo ${i:2}
done
Output of script execution:
$ bash array.sh
outputs.tf
datasources.tf
main.tf
variables.tf