0

I have a myfile which contains lines like

#!/usr/bin/env python3
print("Hello world")
names = ('${(j:', ':)ZSH_VAR[@]}', )

I would like to pre-process this file with the environment variables in my loaded shell (zsh in my case, but a generic bash solution would also work nicely).

How can I do the equivalent of

$ declare -ga ZSH_VAR=( 1 2 3 )
$ preprocess < myfile

Such that the output is

#!/usr/bin/env python3
print("Hello world")
bar=('1', '2', '3', )
3
  • 3
    I'm not sure I understand properly, but are you looking for envsubst? Commented May 11, 2021 at 4:26
  • eval 'bar="$BAR"' or declare 'bar="$BAR"'? Commented May 11, 2021 at 6:04
  • See the TemplateFiles page on the Wooledge wiki. Commented May 11, 2021 at 23:45

1 Answer 1

2

You can use eval for that purpose.

$ BAR=1234 FOO=abcd; while read -r line; do eval 'echo "'"$line"'"'; done < "file"

Or in script. (script.sh)

#!/bin/bash

while read -r line; do eval 'echo "'"$line"'"'"; done < "file"

# If you want to redirect the output into a file (out.txt).
# while read -r line; do eval 'echo "'"$line"'" >> out.txt'; done < "file"
# Or  this
# while read -r line; do eval 'echo "'"$line"'"'; done < "file" > out.txt

Then call the script like this:

FOO=abcd BAR=1234 ./script.sh 

Note

BE CAREFUL. MAKE SURE YOUR FILE DOES NOT CONTAINS rm commands. JUST TO BE SAFE.

Sign up to request clarification or add additional context in comments.

8 Comments

Only to be used if you trust the data, though. Much safer to use envsubst instead; no chance of a $(rm -rf ~) in your file destroying your home directory.
And if you are going to use eval, better to use eval 'echo "'"$line"'"' so you don't have a line containing * HELLO * replace the *s with lists of filenames, or changing tabs to spaces, or deleting leading tabs, or so forth. Which is to say, as currently written, this answer has quite a lot of unexpected/undesired behaviors.
See demonstration of the above issues at ideone.com/mBq9IS
...compare output of above to the less-broken (but still insecure) approach demonstrated at ideone.com/FjpPC0
(Note also the IFS= before the read in the link showing the fixed version -- that stops read from deleting leading and trailing whitespace before it even gets into the line variable!)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.