1

In a bash script foo.sh, invoked by:

y=hi z=hello export z var1=7 x=a ./foo.sh arg1 arg2 

the variables y, var1 and x are set. Is it possible to enumerate all variables that are explicitly set when invoking the script, i.e. var1 and x but not y and not z?

2
  • Are you allowed to change the argument list to script?. One bad-trick would be to find the difference of the env between the parent and within the script inside Commented Mar 27, 2018 at 10:04
  • Has already been suggested below in an answer. Commented Mar 27, 2018 at 10:08

3 Answers 3

1

No, not as is, because bash is doing this seamlessly and those variables aren't really set on the command line (the command line to ./foo.sh).

When bash sees the command line:

var1=7 x=a ./foo.sh arg1 arg2 

it simply runs ./foo.sh arg1 arg2 with those variables already set for it, effectively the same as if you had done:

( export var1=7; export x=a; ./foo.sh arg1 arg2 ) 

except possibly for the number of processes created.

The process running .foo.sh has no idea how those variables were set, it only sees the bit without the variable setting as it's command line.

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

Comments

0

If you run set without arguments in the script, you'll see var1=7 and x=a in the output, but you won't see y=hi there unless y was exported. All the exported variables will be shown, and you can't tell whether they were exported by export or by prepending the assignment to the command.

1 Comment

No, it's not possible, and for a good reason: you'd have had to export all the variables before running a command instead of just listing the assignments before it; and you'll have to unexport them later (or use subshells etc).
0

Due to the order in which variables are tested and expanded, you can use set twice to get the differences. For example:

export y=1 var1=7 x=a /path/to/script.sh $(set) # script.sh oldvars=$@ newvars=$(set) 

var1 and x will be in newvars, but not oldvars. (You will then need to 'diff'the two to find the ones you want).

2 Comments

That's not a bad solution assuming you're allowed to change the arguments to the script. But, if that were the case, I'd probably just suggest passing parameters which do it anyway, rather than environment variables.
Yeah - this is definitely a can be done, not a should be done :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.