bashshell

How do I pass a full set of arguments from one bash script to another when invoked with `bash -c`?


Consider the following two scripts:

Caller.sh

#!/bin/bash

echo "Caller received args $@"
bash -c "./Callee.sh $@"
bash -c './Callee.sh "$@"' "$@"

Callee.sh

#!/bin/bash

echo "Callee received args $@"

Somehow the argument forwarding is broken with this:

./Caller.sh Foo
Caller received args Foo
Callee received args Foo
Callee received args
~/Code/Play master ./Caller.sh Foo Bar
Caller received args Foo Bar
Callee received args Foo
Callee received args Bar

How do I pass the full set of arguments correctly?


Solution

  • Assuming this is a question about how to use bash -c, not just how to call one script from another script: The synopsis for bash -c is:

    bash -c 'command_to_run' 'name_to_use_for_$0' 'arguments_for_command_to_run'
    

    so in your code you need to add a string for bash -c to use to populate the $0 of the subshell it spawns, e.g. using _ (a common choice) as I don't care about its value:

    $ head Caller.sh Callee.sh
    ==> Caller.sh <==
    #!/bin/bash
    
    echo "Caller received args $@"
    bash -c './Callee.sh "$@"' _ "$@"
    
    ==> Callee.sh <==
    #!/bin/bash
    
    echo "Callee received args $@"
    

    $ ./Caller.sh Foo
    Caller received args Foo
    Callee received args Foo
    

    $ ./Caller.sh Foo Bar
    Caller received args Foo Bar
    Callee received args Foo Bar