Recently I was moving my pi sessions to XDG directories and hit an issue putting a Bash script inside a Nix indented string. The script used read -r -d '' to read file paths separated by a null character.

The Bash was valid, but the '' ended the surrounding Nix string, so this didn’t parse:

snippet.nix
pkgs.writeShellScript "list-files" ''
  while IFS= read -r -d '' file; do
    printf '%s\n' "$file"
  done < <(find . -type f -print0)
''
nix 5 lines
"snippet.nix" 5L

To fix this, add another single quote 1:

snippet.nix
pkgs.writeShellScript "list-files" ''
  while IFS= read -r -d ''' file; do
    printf '%s\n' "$file"
  done < <(find . -type f -print0)
''
nix 5 lines
"snippet.nix" 5L

The ''' in the Nix string becomes '' in the generated Bash script. So the empty quotes are preserved without ending the Nix string.

Run the generated script in a directory containing just one file.txt. Expected output is one line, with the space in the filename intact:

snippet.txt
./one file.txt
text 1 line
"snippet.txt" 1L