我想将多个参数作为单个字符串参数传递给 bash 脚本,并传递给外部可执行文件(尤其是git
)
我找到了几个答案,这些答案暗示了这样的事情:
"'$*'"
"'$@'"
传递给外部程序时看起来不错,echo
但传递给外部程序时会失败,即使通过管道传递echo
.
这是一个 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
结果:
$ 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.
如何将多个脚本参数作为单个字符串(包括空格)传递给外部可执行文件(而不将它们包装""
在脚本调用中。
刚刚发现这行得通:
git commit -m "$(echo "'$@'")"
但这使我更上一层楼:
如果没有给出参数,我想省略-m
参数,以便触发提交消息编辑器:
if [ 0 != $# ]
then
MESSAGE ="-m " "$(echo "'$@'")"
fi
git commit $MESSAGE
或者
if [ 0 != $# ]
then
MESSAGE =("-m " "$(echo "'$@'")")
fi
echo
git commit ${MESSAGE[@]}
这甚至失败了,引用的单词也被分开了。:
$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.