Issue
If I define a function in a file, say test1.sh:
#!/bin/bash
foo() {
echo "foo"
}
And in a second, test2.sh, I try to redefine foo
:
#!/bin/bash
source /path/to/test1.sh
...
foo() {
...
echo "bar"
}
foo
Is there a way to change test2.sh to produce:
foo
bar
I know it is possible to do with Bash built-ins using command
, but I want to know if it is possible to extend a user function?
Solution
I'm not sure I see the need to do something like this. You can use functions inside of functions, so why reuse the name when you can just call the original sourced function in a newly created function like this:
AirBoxOmega:stack d$ cat source.file
#!/usr/local/bin/bash
foo() {
echo "foo"
}
AirBoxOmega:stack d$ cat subfoo.sh
#!/usr/local/bin/bash
source /Users/d/stack/source.file
sub_foo() {
foo
echo "bar"
}
sub_foo
AirBoxOmega:stack d$ ./subfoo.sh
foo
bar
Of course if you REALLY have your heart set on modifying, you could source your function inside the new function, call it, and then do something esle after, like this:
AirBoxOmega:stack d$ cat source.file
#!/usr/local/bin/bash
foo() {
echo "foo"
}
AirBoxOmega:stack d$ cat modify.sh
#!/usr/local/bin/bash
foo() {
source /Users/d/stack/source.file
foo
echo "bar"
}
foo
AirBoxOmega:stack d$ ./modify.sh
foo
bar
Answered By - drldcsta Answer Checked By - Willingham (WPSolving Volunteer)