1
#!/bin/sh/

function test() {
       echo BEFORE var1 $var1
       echo BEFORE var1 $var1

       var1=$1
       var2=$2

       echo AFTER var1 $var1
       echo AFTER var1 $var1
}

test 1 2
test 3 4

Result:

BEFORE var1
BEFORE var2
AFTER var1 1
AFTER var2 2
BEFORE var1 1
BEFORE var2 2
AFTER var1 3
AFTER var2 4

Why does var1 and var2 keep the values from the first time the function is called when the second time the function is called? How do I get the variables to clear every time?

2
  • The code you posted and the output cannot have been generated by the same script. Please update your post, so that both match. Commented Dec 8, 2014 at 17:54
  • The shebang cannot end in a /. Commented Dec 8, 2014 at 21:27

2 Answers 2

3

You are looking for the local keyword.

Try

function test() {
       local var1
       local var2
       echo BEFORE var1 $var1
       echo BEFORE var1 $var1

       var1=$1
       var2=$2

       echo AFTER var1 $var1
       echo AFTER var1 $var1
}
Sign up to request clarification or add additional context in comments.

2 Comments

@terence, note that local is a bash command, so change your shebang to #!/bin/bash
function is also a bash keyword.
0

Yet another approach:

test () (
    echo "BEFORE var1 $var1"
    echo "BEFORE var2 $var2"

    var1="$1"
    var2="$2"

    echo "AFTER var1 $var1"
    echo "AFTER var2 $var2"
)

Values of var1 and var2 that exist outside the function will be seen for the "BEFORE" lines, but the changes shown in the "AFTER" lines will be local to the function. This is an all-or-none approach; you cannot change global variables inside the subshell created by the function, but this doesn't require any non-POSIX features.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.