qin
qin

Reputation: 1713

How do I expand variables in a string?

I have two files named proc and env.

In proc:

python -m SimpleHTTPServer $PORT

In env:

PORT=8080

I need to echo the following string (don't exec it) without knowing PORT in file

python -m SimpleHTTPServer 8080

Upvotes: 1

Views: 192

Answers (3)

You can use the follow command:

export $(cat env) && eval echo $(cat proc)

Upvotes: 1

Jens
Jens

Reputation: 72629

If you don't have envsubst, you can use this little one-liner, which works on any POSIX shell.

$ . ./env; eval echo $(cat proc)
python -m SimpleHTTPServer 8080

All caveats about eval apply, i.e. you should make sure proc is safe to eval without unwanted side-effects. Limitations: will work only with a one line proc and may change some white-space between arguments to a single blank.

Upvotes: 2

Freddy
Freddy

Reputation: 4688

You could source the env file, export the PORT variable and use envsubst to substitute the variable in proc. This is run in a subshell to keep your environment clean.

(. ./env; export PORT; envsubst '$PORT' <proc)

Output:

python -m SimpleHTTPServer 8080

Upvotes: 3

Related Questions