Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash, call a function sourced from a script?

Tags:

function

bash

Say I have 2 scripts

test1.sh

#!/bin/sh
. ./test2.sh
foo

test2.sh

#!/bin/sh
foo(){
  echo "bar"
}

If I call first script it is ok

$ ./test1.sh
bar

But if I try to call foo after that it will not work.

$ foo
bash: foo: command not found
like image 634
Zombo Avatar asked Dec 12 '22 00:12

Zombo


1 Answers

When you execute ./test1.sh, a subprocess is spawned. When test1.sh sources test2.sh, only the context of that subprocess is modified when foo() is defined. As soon as test1.sh completes, the subprocess terminates and your interactive shell has no knowledge of foo().

like image 110
mouviciel Avatar answered Dec 18 '22 02:12

mouviciel