Skip to main content

Safe Scripting (Null Bytes)

When integrating fd into automated shell scripts (.sh files), you must account for the fact that Linux filenames can legally contain spaces, tabs, and even newline characters.

If fd outputs a file named My Document.txt, and you pipe that output to a while loop or xargs, the pipeline will split the string at the space, resulting in catastrophic failures (e.g., trying to delete a file named "My").

The -0 Flag (--print0)

To guarantee absolute safety, you must use the -0 flag.

-0 instructs fd to separate each output result with a null byte (\0) instead of a newline character (\n). Because the null byte is the only character strictly forbidden in Linux filenames, it serves as a flawless delimiter.

Piping to Xargs

When passing data to xargs, you must pair fd -0 with xargs -0.

# 100% safe pipeline, immune to spaces or newlines in filenames
fd -e tmp -0 | xargs -0 rm

Note: While fd -X rm is generally preferred over xargs, xargs is still useful when you need to construct highly complex parallel pipelines that fd's internal engine doesn't support.

The Null-Delimited While Loop

If your script requires executing multiple commands per file, xargs is insufficient. You must use a while read loop.

To read null-delimited data safely in Bash, use IFS= read -r -d ''.

#!/bin/bash

# Find all PNG files, safely handling spaces
fd -e png -0 | while IFS= read -r -d '' file; do
echo "Processing image: $file"

# 1. Optimize image
optipng "$file"

# 2. Upload to S3
aws s3 cp "$file" s3://my-bucket/images/

# 3. Log success
echo "Uploaded $file" >> /var/log/upload.log
done

Breakdown of the Loop Syntax:

  • IFS=: Clears the internal field separator to preserve leading/trailing whitespace.
  • -r: Disables backslash escaping.
  • -d '': Instructs the read command to delimit by the null byte.
Golden Rule

Never use a standard for loop (for file in $(fd pattern); do ...) in a shell script. Always use fd -0 with xargs -0 or a null-delimited while loop.