Stop Using eval to Parse Data from Files

Shell Scripting & Automation

Stop Using eval to Parse Data from Files

Technical Briefing | 7/11/2026

We have all seen it. A script grabs a config file or a list of variables from a flat file, hits it with eval, and moves on. It feels like a quick win until your source file has an extra semicolon or a stray variable expansion you did not account for. I once spent four hours debugging a script that accidentally wiped a directory because someone put a dollar sign in a comment inside a sourced config file. It is a lazy pattern that invites command injection and logic errors that are notoriously hard to trace in production.

The safer way to load key-value pairs

Instead of executing arbitrary code, treat your data like data. If you have a file with key equals value entries, use a while read loop combined with a little IFS magic. This keeps the execution environment separate from the input and prevents the shell from interpreting your data as instructions. If you need to handle complex nested structures, move to jq or a proper tool, but for simple config files, this is the way.

while IFS='=' read -r key value; do [[ "$key" =~ ^[^#] ]] && declare "$key"="$value"; done < config.file

  • IFS= controls how read splits the line, which is why we target the equals sign
  • The regex check ^[^#] ensures we skip commented lines before declaring variables
  • Using read -r prevents backslash escaping which often messes up file paths
  • Declaring the variable after reading ensures you control exactly what enters the scope

This approach is slightly more verbose than just sourcing a file, but it is deterministic. If you are dealing with environment-specific overrides, check the input keys against a whitelist before you declare them. You will save yourself the headache of weird bugs during a deployment when someone decides to add a clever comment to a file your script is supposed to ingest. Keep your parser predictable and the gremlins stay out.

Linux Admin Automation  |  © www.ngelinux.com  |  7/11/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted