bash - 将 Bash 脚本中的命令选项与字符串分开

标签 bash git

我正在寻找一种方法来编写一个调用 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/

相关文章:

bash - 在 shell 脚本之间共享变量

git - 当有人从我的 git 提交中挑选并提交了他们自己的提交时,我该如何 merge ?

Git 拒绝用户创建标签

linux - 获取自 Linux 上的 Epoch、Bash 以来的当前时间(以秒为单位)

linux - shell脚本单独列出目录中的文件名并重命名

git - Bitbucket 服务器 pull 请求

git - svn diff 或 git diff 中带有 at 符号的 “@@…@@” meta 行是什么意思?

git - 我如何重写历史记录,以便所有文件(我已经移动的文件除外)都位于子目录中?

BASH 将变量传递给函数

ios - 当提示输入远程主机的 SCP 密码时,如何将回车添加到 bash?