Home > other >  How do I call a bash function from bazel sh_binary?
How do I call a bash function from bazel sh_binary?

Time:10-10

I would like to call a bash function from sh_binary, but can't figure out how.

I have bash script with function calls:

mybashfunction.sh

function a () {
  echo a
}

function b () {
  echo b
}

BUILD.bazel

sh_binary(
    name = "a",
    srcs = ["mybashfunction.sh"],
    args = [
        "a",
    ],
    visibility = ["//visibility:public"],
)

The following run doesn't call the bash a function:

bazel run //test:a

Returns:

INFO: Analyzed target //test:a (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //test:a up-to-date:
  bazel-bin/test/a
INFO: Elapsed time: 0.148s, Critical Path: 0.00s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total action
INFO: Build completed successfully, 1 total action

The only way I can make it work is to call the function from another script:

a.sh

source ./test/mybashfunction.sh
a

BUILD.bazel

sh_binary(
    name = "a",
    srcs = ["a.sh"],
    data = [
        "mybashfunction.sh",
    ],
    visibility = ["//visibility:public"],
)

Output:

bazel run //test:a
INFO: Analyzed target //test:a (1 packages loaded, 3 targets configured).
INFO: Found 1 target...
Target //test:a up-to-date:
  bazel-bin/test/a
INFO: Elapsed time: 0.192s, Critical Path: 0.02s
INFO: 4 processes: 4 internal.
INFO: Build completed successfully, 4 total actions
INFO: Build completed successfully, 4 total actions
a

CodePudding user response:

Not the cleanest way, but one possible solution would be to extend your script to accept the function to be run as argument, e.g.

function a () {
  echo a
}

function b () {
  echo b
}

if [ ! -z "$1" ]; then
  $1
fi

Since you're passing the argument to the script in the BUILD file, this should trigger the call to the function:

sh_binary(
    name = "a",
    srcs = ["mybashfunction.sh"],
    args = [
        "a",
    ],
    visibility = ["//visibility:public"],
)

sh_binary(
    name = "b",
    srcs = ["mybashfunction.sh"],
    args = [
        "b",
    ],
    visibility = ["//visibility:public"],
)
$> bazel run :a
...
INFO: Build completed successfully, 1 total action
a

$> bazel run :b
...
INFO: Build completed successfully, 1 total action
b

  • Related