title: Why are bash variables not global if sourced script runs in a function?
body: <p>Sourcing a file normally from another script, I can access its variables.</p>
  <p>If I source a script from within a function, its variables <em>aren't</em> global, which seems to contradict the manpage:</p>
  <blockquote>
  <p><strong>FUNCTION</strong> Variables local to the function may be declared with the local builtin command.  Ordinarily, variables and their values are shared between the function and its caller.</p>
  <p><strong>source filename [arguments]</strong> Read and execute commands from filename in the current shell environment</p>
  </blockquote>
  <p>Happens with all my conveniently available versions: 3.2.57(1)-release (x86_64-apple-darwin17), 4.3.42(1)-release (x86_64-suse-linux-gnu), and version 4.3.48(1)-release (x86_64-pc-linux-gnu)</p>
  <p>test-sourced.sh:</p>
  <pre><code>#!/bin/bash
  echo $BASH_SOURCE $$ $SHLVL
  declare -x FOO=bar
  foo() { echo funfoo=$FOO $$ $SHLVL ; }
  </code></pre>
  <p>test-top.sh:</p>
  <pre><code>#!/bin/bash
  echo $BASH_SOURCE $$ $SHLVL
  
  funcsource () { source ./test-sourced.sh ; }
  echo ==== funcsource...
  funcsource
  echo foo=$FOO
  foo
  
  echo ==== source...
  source ./test-sourced.sh
  echo foo=$FOO
  foo
  </code></pre>
  <p>I see this output, but expected to see both funcsource and source do the same thing:</p>
  <pre><code>$ ./test-top.sh 
  ./test-top.sh 1234 2
  ==== funcsource...
  ./test-sourced.sh 1234 2
  foo=
  funfoo= 1234 2
  ==== source...
  ./test-sourced.sh 1234 2
  foo=bar 1234 2
  funfoo=bar
  </code></pre>
  <p>It's the same PID and the same shell level, so it looks like deliberate behaviour. Is this a bug, or am I missing something?</p>
  <hr />
  <p>Update: echoing $FOO and running 'foo' in the function immediately after the <code>source</code> command DOES give their values, so they're getting that far but are for some reason kept local to the function scope. Which still seems to contradict the manual.</p>