I want to pass multiple arguments to a bash script as a single string parameter to an external executable (especially git)
I found several answers that suggest something like this:
"'$*'"
"'$@'"
which looks pretty good when passing to echo but fails when passed to an external programm, even if piped through echo.
This is a MWE:
#!/bin/bash
# preparation
git init .
git add -A
echo git commit -m "'$@'" # works when copied to terminal
git commit -m "'$@'" # fails if more than one parameter given
git commit -m $(echo "'$@'") # fails if more than one parameter given
rm -rf .git # c
reults in:
$ bash test.sh test2 test2
empty Git-Repository in /tests/bash-scripts/.git/ initialized
git commit -m 'test1 test2'
error: pathspec 'test2'' did not match any file(s) known to git.
error: pathspec 'test2'' did not match any file(s) known to git.
How do I pass multiple script parameters as a single string (including spaces) to an external executable (without wrapping them in "" in the script call.
Just found out that this works:
git commit -m "$(echo "'$@'")"
but that leads me to the next level:
I want to ommit the -m parameter if no arguments are given so that the commit message editor is triggered:
if [ 0 != $# ]
then
MESSAGE ="-m " "$(echo "'$@'")"
fi
git commit $MESSAGE
or
if [ 0 != $# ]
then
MESSAGE =("-m " "$(echo "'$@'")")
fi
echo
git commit ${MESSAGE[@]}
this again fails even wose, the quoted words are also separated.:
$bash test.sh "test1 test2" test3
git commit -m 'test1 test2 test3'
error: pathspec 'test2' did not match any file(s) known to git.
error: pathspec 'test3'' did not match any file(s) known to git.