0

This question already has an answer here:

Let's check the following script:

#!/bin/sh

func()
{
  echo "var: $var";
}

var="val" func

echo "after executing the command, var: $var"

Its output is:

var: val
after executing the command, var: val

The var variable is left set after executing the command.

Is it correct behavior? I thought that command scope variables are set just for a single command.

If I use bash (set #!/bin/bash in the first line) instead of sh then setting a variable for a command doesn't affect the rest of the script:

var: val
after executing the command, var: 

In the busybox implementation sh and bash work equally: the variable is left assigned after executing the command.

To workaround the problem I use parentheses when executing such commands:

(var="val" func)

This way the var variable isn't touched in all shells.

marked as duplicate by muru, John1024 bash Mar 16 '18 at 3:59

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • "In bash, this is done only in bash mode, not in POSIX mode", and your shebang is /bin/sh. – muru Mar 16 '18 at 3:35
  • I don't agree that my question is duplicate, but the accepted answer in the linked question fully satisfies me! Thank you! – anton_rh Mar 16 '18 at 4:33
  • @anton_rh Glad it worked for you. – John1024 Mar 16 '18 at 4:42
  • 1
    it's a dupe because even though the variable name differs, it's the same problem with the same explanation/solution. – cas Mar 16 '18 at 4:42

Browse other questions tagged or ask your own question.