0

I want to write a bash function that executes an arbitrary commands on multiple branches.

compare_command () {
    branch2="$1"
    shift
    command="$@"
    echo $branch2
    echo $command
    # assume $@ is command and args
    $(command) 2>&1 | tee baseline.log
    git checkout "$branch2"
    $(command) 2>&1 | tee "$branch2".log
    git checkout -
}

compare_command master ls, for example, fails with "command not found: 1" compare_command master ls -a, fails with "command not found: ls -a"

  • Going by the output you say you get, that's not the function you're actually running. – muru Dec 29 '20 at 17:01
  • You can't expect to be able to assign the list "$@" to a string and then use it as a command. Also, $(command) runs the command built-in command and nothing else. As muru says, you don't appear to be running the code you are showing. – Kusalananda Dec 29 '20 at 17:15
  • Is there a way to assign the command to one variable and all args to another variable and then $(command "$args") or some such? – Sam Shleifer Dec 29 '20 at 17:20
  • Use an array, not a string variable. See https://unix.stackexchange.com/questions/444946 Consider showing us the actual code that you run though. – Kusalananda Dec 29 '20 at 17:25
  • Your question is not clear: What do you mean by branches? What type of branches? Tell us what you are trying to achieve, then show what you have tried. – ctrl-alt-delor Dec 29 '20 at 18:34

1 Answers1

4

I assume you are just confused how brackets are used in bash

compare_command () {
    branch2="$1"
    shift
    echo "$branch2"
    echo "$@"
    # assume $@ is command and args
    "$@" 2>&1 | tee baseline.log
    git checkout "$branch2"
    "$@" 2>&1 | tee "$branch2".log
    git checkout -
}
Kusalananda
  • 333,661
Marco
  • 461