mtrics
mtrics

Reputation: 25

Separating command options from strings in a Bash script

I'm looking for a way to write a function calling git commit with several messages ; for example :

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" 

Etc.

The thing is, I have trouble finding an efficient way to express in the script what's the option (-m) and what's the string/message.

Here's what I have so far :

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
}

The function would be called by executing :

commit "Commit headline" body="1st paragraph for the commit|2nd paragraph"

The problem is that, in my function, the "-m" argument is considered as a string by the git commit command. But if I take it out of the "echo" string, then it will become an argument of the echo command, which is not what I want.

Do you have any pointers on how to bypass this?

Upvotes: 2

Views: 64

Answers (1)

chash
chash

Reputation: 4423

Perhaps something like this would work:

#!/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'

Upvotes: 4

Related Questions