I have a script and am passing a command that I want to then run within the script.
Passing the function like:
bash ./myscript.sh 'yarn test'
I can run the command if I first save it as a variable and then run it like:
FUNC=$1
$FUNC
But can't seem to figure out how to just run it without first saving it.
EDIT:
I should have been more specific with my example, my code more accurately looks like: (using KamilCuk's reply suggestion)
run_command () {
"$@"
}
run_command
Having the value inside of a function in the script won't run the passed command, having it outside as simply "$@" will run it.
Is there something different I would need to do to have it run within the function?
$1as a command? BTW, you are not passing a function, but the name of a function, which is something different. Functions are not first-class objects in bash, and can't be passed around.$1and it doesn't run it.I can run the functionit's not a function, it's a command. And you should rather prefer passingbash ./myscript.sh yarn testand then do"$@"to properly handle corner cases, like spaces or*characters in arguments../myscript.sh yarn testand run"$@". Otherwise you'll have serious problems when trying to pass arguments with quotes and spaces. Which, now that I read, @KamilCuk already told you. :)