Skip to content

Refactor env module to be shell-agnostic #65

@peter-bread

Description

@peter-bread

Probably use some kind of simple key-value pairs, read the file in at shell start up, parse it to get key and value, then use shell's mechanism to set the variables.

This may not be possible (specifically dynamic keys). This would require parsing the file and then generating a separate file that contains valid shell, e.g.

# Assume file is already parsed
KEY="foo"
VAL="bar"

echo "export $KEY=$VAL" > env.generated

After some testing, something like this could work:

# ENV.txt

# Rules:
# 1. KEY=VAL
# 2. No quotes
# 3. Comments start with a #

FOO   =   $HOME
BAZ   =   $HOME
# parser.sh

ENV_FILE="./ENV.txt"

while IFS=' ' read -r entry; do
  # These read as assertions, i.e. the conditions must be true to make it
  # to the main body of the loop
  [[ $entry != \#* ]] || continue
  [[ $entry == *=* ]] || continue

  KEY=$(echo "$entry" | cut -d= -f1 | tr -d "[:blank:]") # You can use tr...
  VAL=$(echo "$entry" | cut -d= -f2 | awk '{$1=$1};1')   # ...or awk to trim whitespace.
  echo "export $KEY=\"$VAL\"" > env.generated
done <"$ENV_FILE"
# env.generated

export FOO="$HOME"
export BAZ="$HOME"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions