0

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.

anton_rh
  • 409
  • "In bash, this is done only in bash mode, not in POSIX mode", and your shebang is /bin/sh. – muru Mar 16 '18 at 03: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 04:33
  • @anton_rh Glad it worked for you. – John1024 Mar 16 '18 at 04: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 04:42

0 Answers0