0

I want to use fakeroot for a project, but the project has lots of functions and variables that I need to pass through to fakeroot.

#!/bin/bash
myVar="foo"

function testFunction() {
    echo "$myVar"
}

fakeroot -- bash -c testFunction

but it doesn't run testFunction or echo out myVar

Plasma
  • 121
  • 6
  • 1
    This is a false problem: `fakeroot` isn't causing this. You could remove `fakeroot` and you'd get the problem simply with `bash -c testFunction`. So it probably falls into https://xyproblem.info/ category. You're trying to solve with Y, what's the actual X? Anyway, you can run your whole script with fakeroot outside of it to solve this (and also remove bash -c of course) – A.B Jul 11 '21 at 18:41
  • Then how does `makepkg` do it? – Plasma Jul 14 '21 at 19:41

2 Answers2

1

You could also use bash's exported function feature. However, given that fakeroot is an sh script, you'd need to be on a system where the sh implementation doesn't strip those BASH_FUNC_fname%% variables from the environment like dash does. To make sure it doesn't happen you could have fakeroot interpreted by bash itself as bash -o posix which is a sh interpreter.

#!/bin/bash -
myVar="foo"

testFunction() {
    printf '%s\n' "$myVar"
}

export myVar
export -f testFunction

fakeroot=$(command -v fakeroot)
bash -o posix -- "${fakeroot:?fakeroot not found}" -- bash -c testFunction

Note that you also need to export myVar for that to be available to the bash started by fakeroot. Instead of calling export for both myVar and testFunction, you could also issue a set -o allexport before declaring them.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
0

OK, I figured it out:

#!/bin/bash
myVar="foo"

function testFunction() {
    echo "$myVar"
}

tmp_function=$(declare -f testFunction)
fakeroot -- bash -c "$tmp_function; testFunction"
Plasma
  • 121
  • 6
  • 1
    You'd also need to include the output of `declare -p myVar` to propagate that variable's definition to the `bash` shell started by `fakeroot`. – Stéphane Chazelas Jul 25 '21 at 14:06