8

I have var.sh

name="John"
age="29"

I also have main.sh

eval "var.sh"
echo "My name is $name"

When I run, I kept getting

⚡️  Desktop  bash main.sh 
main.sh: line 1: var.sh: command not found
My name is 

What is the best practice to import a local bash file into another bash file ?

Is there way that will work on Mac OS X, Linux and Windows ?

code-8
  • 54,650
  • 106
  • 352
  • 604

1 Answers1

10

eval is not meant for importing a script into another. You need the source builtin:

source var.sh

which is synonymous to:

. var.sh

eval is throwing the error for one or both of these reasons:

  • var.sh is not executable
  • var.sh is executable but current directory is not in the PATH

Even if we address both of these issues, eval will spawn a shell to run var.sh which means all the variables set inside var.sh are forgotten once eval finishes and that's not what you want.


Output of help source:

source: source filename [arguments]

Execute commands from a file in the current shell.

Read and execute commands from FILENAME in the current shell.  The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.
codeforester
  • 39,467
  • 16
  • 112
  • 140