0

I have a file .foo.sh that only contain exports, i.e.

export foo="../../../../"
export bar="a/b/c/d/"
export baz="a/b/c/d/e/f"

In a script this file is sourced like this (I have verified that it isn't something else in the script affecting it, with a test script that does only this):

!#/bin/bash
cd u/v/x/y/z/
source .foo.sh

But the environment variables are set incorrectly. If I add echo "foo $foo bar $bar baz $baz" before and after sourcing, I get this output:

foo  bar  baz 
foo . bar .. baz ../e/f

If I add cat .foo.sh so that the script looks like this:

!#/bin/bash
cd u/v/x/y/z/
cat .foo.sh
echo "foo $foo bar $bar baz $baz"
source .foo.sh
echo "foo $foo bar $bar baz $baz"

I get this output:

export foo="../../../../"
export bar="a/b/c/d/"
export baz="a/b/c/d/e/f"
foo  bar  baz 
foo . bar .. baz ../e/f

If I replace the source line with the .foo.sh contents, like this:

!#/bin/bash
cd u/v/x/y/z/
echo "foo $foo bar $bar baz $baz"
export foo="../../../../"
export bar="a/b/c/d/"
export baz="a/b/c/d/e/f"
echo "foo $foo bar $bar baz $baz"

I get this output:

foo  bar  baz 
foo ../../../../ bar a/b/c/d/ baz a/b/c/d/e/f

Why are the paths changed to be relative to another directory when exported in a sourced file, compared to when just exported inline, even though the sourced file is in the CWD and the exported paths are hardcoded strings?

1 Answer 1

2

There was a file named .foo.sh in a directory listed in my PATH, that exported the same variables, but with other values. Turns out, just like running a normal command, when sourcing a file the shell first looks in the PATH for a file with a matching name. This is extra confusing considering which .foo.sh doesn't return anything, like it would for an executable file. But changing the script to source like this source ./.foo.sh fixed the issue.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.