我正在寻找一种方法来编写一个调用 git commit 并包含多条消息的函数;例如:
git commit -m "This is the commit headline" -m "This is a new paragraph for the commit" -m "Adding paragraphs makes it easier to give details"
等等
问题是,我很难找到一种有效的方法来在脚本中表达什么是选项(-m)以及什么是字符串/消息。
这是我到目前为止所拥有的:
function commit(){
if [[ $# > 1 ]]
then
commit_body=`echo $2 | cut -d '=' -f 2`
IFS='|' read -r -a paragraphs <<< "$commit_body"
git commit -m "$1" $(for p in "${paragraphs[@]}"; do echo -n "-m $p"; done)
else
git commit -m "$1"
fi
}
该函数将通过执行来调用:
commit "Commit headline" body="1st paragraph for the commit|2nd paragraph"
问题是,在我的函数中,“-m”参数被 git commit 命令视为字符串。但如果我把它从“echo”字符串中取出来,那么它将成为 echo 命令的参数,这不是我想要的。
您有关于如何绕过此问题的任何指示吗?
最佳答案
也许这样的事情会起作用:
#!/bin/bash
function commit() {
options=("-m" "$1")
if [[ $# > 1 ]]
then
commit_body=`echo "$2" | cut -d '=' -f 2`
IFS='|' read -r -a paragraphs <<< "$commit_body"
for msg in "${paragraphs[@]}"
do
options+=("-m" "${msg}")
done
fi
git commit "${options[@]}"
}
commit "Commit headline" body="1st paragraph for the commit|2nd paragraph"
$ bash -x commit.sh
+ commit 'Commit headline' 'body=1st paragraph for the commit|2nd paragraph'
+ options=("-m" "$1")
+ [[ 2 > 1 ]]
++ echo 'body=1st paragraph for the commit|2nd paragraph'
++ cut -d = -f 2
+ commit_body='1st paragraph for the commit|2nd paragraph'
+ IFS='|'
+ read -r -a paragraphs
+ for msg in "${paragraphs[@]}"
+ options+=("-m" "${msg}")
+ for msg in "${paragraphs[@]}"
+ options+=("-m" "${msg}")
+ git commit -m 'Commit headline' -m '1st paragraph for the commit' -m '2nd paragraph'
关于bash - 将 Bash 脚本中的命令选项与字符串分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61636776/