The issue in your script is that myVariable is defined inside the function my_test(), so its scope is limited to that function. To make the variable accessible outside the function, you need to declare it as global or ensure it is set in the global scope.
myVariable as global inside the functionbashecho "myVariable: $myVariable|" my_test() { local myVariable=true # This makes it local to the function # To make it global, remove 'local' or explicitly declare it as global myVariable=true } my_test echo "myVariable: $myVariable|"
However, by default, variables in Bash are global unless declared as local. So if you remove local, it will work as expected.
myVariable globally before the functionbashmyVariable=false # Set globally echo "myVariable: $myVariable|" my_test() { myVariable=true # This will modify the global variable } my_test echo "myVariable: $myVariable|"
export to make it available in subshells (if needed)If you want the variable to be available in subshells, you can use export:
bashexport myVariable=false echo "myVariable: $myVariable|" my_test() { myVariable=true } my_test echo "myVariable: $myVariable|"
Here’s the corrected version of your script:
bashecho "myVariable: $myVariable|" my_test() { myVariable=true } my_test echo "myVariable: $myVariable|"
Output:
textmyVariable: | myVariable: true|
The key is to call the function (my_test) before the second echo. Otherwise, myVariable remains unset.
Vibe can make mistakes. Check answers. Learn more