Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a function be extended in Bash?

Tags:

bash

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?

like image 990
MrAlias Avatar asked Aug 07 '14 04:08

MrAlias


1 Answers

I don't know of a nice way of doing it (but I'd love to be proven wrong).

Here's an ugly way:

# test2.sh
# ..
eval 'foo() {
        '"$(declare -f foo | tail -n+2)"'

        echo bar
      }'
like image 155
rici Avatar answered Sep 27 '22 21:09

rici