Reputation: 524
Suppose I have a lot scripts: 1.sh,2.sh 3.sh, ..., n.sh, and I want to use them this way:
./1.sh | 2.sh | 3.sh | ... | n.sh
I'd like to share variables from 1.sh to the others.
I tried to export the variables. The problem is: I don't want them to exist after the last completes. It would be easy to make n.sh to erase them, but it sounds a workaround to me.
There are a lot of answers with solutions here on Stack Overflow, but neither of them goes round to me.
All in all, I'm asking if there is a way of constructing variables that work only for a sequence of commands with pipes.
Is there a way of doing this without workarounds?
Upvotes: 0
Views: 21
Reputation: 2868
Give this a try:
( MYVAR=42; export MYVAR ; ./1.sh | 2.sh | 3.sh | ... | n.sh )
The shell creates a first subshell to execute scripts in the ( ... )
MYVAR
is then only defined inside the subshell, and it is visible to all scripts. Its lifetime is the same as the first subshell.
Anychange to MYVAR
during execution of one of the 1.sh
... n.sh
script is not visible outside: in other words, if 1.sh
modifies the value of MYVAR
, then 2.sh
and other scripts are only seeing the oringinal value (42 in the example).
Upvotes: 1
Reputation: 2187
Put it all into ( ./1.sh | 2.sh | 3.sh | ... | n.sh )
parenthes and set all variables to your taste after the opening (
- ( ) is a subshell and thus after the end, nothing from the environment is left - no need to "remove" anything.
Upvotes: 0