Issue
I basically want to do bash -c "$@"
, but that doesn't work (my command does not get run). While eval "$@"
works fine, what's the difference?
I want to do something like this:
myscript:
function run_it() {
bash -c "$@"
}
run_it $@
./myscript MY_VAR=5 make my-target
Solution
It's because of the quoting. This should work better:
function run_it() {
bash -c "$*" # Change 1
}
run_it "$@" # Change 2
The reason for change 1: $@
is special when used inside quotes, like "$@"
. Rather than expanding to a single argument, it expands to a series of quoted arguments: "MY_VAR=5" "make" "my-target"
. As a result, the -c
flag only receives the MY_VAR=5
part, which is executed with make
and my-target
as arguments $0
and $1
respectively. By using "$*"
you do end up with a single string. Note that this still doesn't handle spaces correctly; not sure how to fix that.
The reason for change 2: Here we do want every argument to be quoted individually. This makes sure that arguments aren't being split too soon. It might be pointless until you fix the other spaces issue first though.
Answered By - Thomas Answer Checked By - Marie Seifert (WPSolving Admin)