xdevs23 xdevs23 - 4 months ago 8
Bash Question

How to get the content of a function in a string using bash?

I have already searched about this particular problem, but couldn't find anything helpful.

Let's assume I have following functions defined in my

~/.bashrc
(Note: this is pseudo-code!):

ANDROID_PLATFORM_ROOT="/home/simao/xos/src/"

function getPlatformPath() {
echo "$ANDROID_PLATFORM_ROOT"
}

function addCaf() {
# Me doing stuff
echo "blah/$(getPlatformPath)"
}

function addAosp() {
# Me doing stuff
echo "aosp/$(getPlatformPath)"
}

function addXos() {
# Me doing stuff
echo "xos/$(getPlatformPath)"
}

function addAllAll() {
cd $(gettop)
# repo forall -c "addCaf; addAosp; addXos" # Does not work!
repo forall -c # Here is where I need all those commands
}


My problem:

I need to get the functions
addCaf
,
addAosp
and
addXos
in one single line.

Like you can run following in bash (pseudo code):

dothis; dothat; doanotherthing; trythis && succeedsdothis || nosuccessdothis; blah


I would like to run all commands inside the three functions
addCaf
,
addAosp
and
addXos
in just one line.

Any help is appreciated.

What I already tried:

repo forall -c "bash -c \"source ~/.bashrc; addAllAll\""


But that didn't work as well.

Edit:

To clarify what I mean.

I want something like that as a result:

repo forall -c 'function getPlatformPath() { echo "$ANDROID_PLATFORM_ROOT"; }; ANDROID_PLATFORM_ROOT="/home/simao/xos/src/"; echo "blah/$(getPlatformPath)"; echo "aosp/$(getPlatformPath)"; echo "xos/$(getPlatformPath)"'


But I don't want to write that manually. Instead, I want to get those lines from the functions that already exist.

agc agc
Answer

Make a dummy function foo(), which just prints "bar":

foo() { echo bar ; }

Now a bash function to print what's in one (or more) functions. Since the contents of a function are indented with 4 spaces, sed removes any lines without 4 leading spaces, then removes the leading spaces as well, and makes sure every line ends with a ';' :

# Usage: in_func <function_name1> [ ...<function_name2> ... ]
in_func() 
    { while [ "$1" ] ; do \
          type $1 | sed  -n '/^    /{s/[^;]$/&\;/;s/^    //p}' ; shift ; \
      done ; }

Print what's in foo():

in_func foo

Output:

echo bar;

Assign what's in foo() to the string $baz, then print $baz:

baz="`in_func foo`" ; echo $baz

Output:

echo bar;

Run what's in foo():

eval "$baz"

Output:

bar

Assign what's in foo() to $baz three times, and run it:

baz="`in_func foo foo foo`" ; eval "$baz"

Output:

bar
bar
bar
Comments