1

I have bash script: myscript.sh. Here is the content:

#!/bin/bash

function my_func {
    echo "my_func start"
    echo $MY_VARIABLE  # THIS PRINTS NOTHING
    echo "my_func end"
}

function func2 {
}

echo "after my_func"
echo $MY_VARIABLE # this prints "YES"

I want to call only function my_func from command line with environment variable "MY_VARIABLE". I launch script with this command:

MY_VARIABLE=YES source myscript.sh; my_func

Here is the output:

after my_func
YES
my_func start

my_func end

Variable $MY_VARIABLE inside my_func() is empty. I want that variable $MY_VARIABLE in my_func() were equal to "YES".

1
  • What documentation leads you to the expectation that your original code would work as described? Commented Nov 22, 2019 at 14:46

1 Answer 1

3

You are only setting MY_VARIABLE for the environment in which source runs. Once that complete, my_func runs in your original environment. If you want my_func to have access, use

export MY_VARIALBE=YES; source my script.sh; my_func

bash doesn't have closures; when you define my_func, the shell isn't using the current value of MY_VARIABLE in the definition. It just creates a function that, when called, looks in the calling scope for the value.

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

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.