-1

Let's say I have the following two commands:

A=1 B=2 C=3 run-app1.py
A=1 B=2 C=3 run-app2.py

I'd love to dry this out so I only need to update the variables in one place (and not risk them getting out of sync). Something like:

VALUES = get-values.sh

VALUES run-app1.py
VALUES run-app2.py

How can I do this?

2
  • 3
    This question is similar to: How to write a bash script to set global environment variable?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Sep 10, 2024 at 20:49
  • Write a script run_with_values which will invoke the passed as argument program with the values you want as in ./run_with_values run-app1.py Commented Sep 10, 2024 at 20:52

2 Answers 2

3

Export all the variables then run the scripts:

export A=1 B=2 C=3
run-app1.py
run-app2.py
Sign up to request clarification or add additional context in comments.

5 Comments

If it's an issue, you can also do all this in a single subshell (export ...; run-app1.py; run-app2.py), which limits the scope of the environment changes.
Yeah. I was kind of surprised you can't do that as a prefix, like A=1 { command1; command2; } or A=1 (command1; command2)
If I ever knew the rationale for restricting precommand assignments to simple commands, I've forgotten it.
Yes. The POSIX shell language associates variable assignments specifically with simple commands, as it defines those, but makes no provision for doing the same with compound commands. The Bash manual is not clear on that, but its man page follows the POSIX wording pretty closely. I don't know the rationale, if any. Possibly contributing to confusion here is that redirections can be applied both to simple commands and compound commands, but the documentation provides for those two cases separately, not generically for all commands.
I'm not surprised, shell syntax is kind of a mess, probably because it evolved organically.
1

Try this :

vars=("A=1" "B=2" "C=3")
env "${vars[@]}" run-app1.py
env "${vars[@]}" run-app2.py

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.