0

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?

1
  • There is a way: use command grouping, see my answer. Commented Jun 5, 2016 at 23:40

2 Answers 2

1

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).

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.