Site icon New Generation Enterprise Linux

Stop your scripts from eating the wrong files when glob expansion goes sideways

Shell Scripting & Automation

Stop your scripts from eating the wrong files when glob expansion goes sideways

Technical Briefing | 8/19/2026

You have likely written a loop that iterates over files using a standard wildcard. It works perfectly in staging with three text files. But then you drop it into a directory containing filenames with spaces, newlines, or leading hyphens, and suddenly your production script is either throwing errors or, worse, modifying the wrong data. Most people fix this by wrapping variables in quotes and calling it a day, but that is not always enough.

Why wildcards are not your friends

The shell performs word splitting and pathname expansion before your command even sees the arguments. If you have a file starting with a dash, the command you are running might interpret that filename as a flag. I once saw a backup script attempt to delete a set of logs that accidentally included a file named -rf. It did not end well. You need to explicitly tell your tools where the filenames start and stop.

for f in ./*.log; do [ -e "$f" ] && command_name -- "$f"; done
  • Always use the — delimiter to signal the end of command options.
  • Check that the file exists with -e before acting to avoid processing literal patterns like *.log when no matches are found.
  • Prefer using null-terminated strings with find -print0 if you have to handle complex directory trees.

Using the — flag is a tiny change that saves hours of post-mortem analysis. When you are writing automation that touches user-generated content, assume every filename is malicious or malformed. If you are still relying on for f in * without safety checks, audit your scripts today before a rogue file name becomes your next outage.

Linux Admin Automation  |  © www.ngelinux.com  |  8/19/2026
0 0 votes
Article Rating
Exit mobile version