Search code examples
bashfunctionshellaliasstring-concatenation

.profile function duplicates my argument in a string concat?


I use Git commit issue numbers in alignment with GitHub issues. To save time I wrote a bash function to creating a commit message like this:

git commit -m "#4 my commit message"

when calling

gci 4 "my commit message"

where 4 is the issue number, and the commit message follows.

However, my current implementation:

alias gcm='git commit -m '
gci(){
    index="${@:1}"
    message="#$index ${@:2}"
    gcm "$message"
}

yields the commit message twice:

$ gci 4 "my commit message"
[iss2 79d9540] #4 my commit message my commit message
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 h.z

What is causing the message to repeat twice?


Solution

  • The ${@:1} and ${@:2} does not work as you expect, use $1 for first parameter and $2 for the second:

    alias gcm='git commit -m '
    gci(){
        index="$1"
        message="#$index $2"
        gcm "$message"
    }
    

    As a side note, alias will not work in noninteractive shells.
    No as to ${@:1}, from here:

    ${var:pos}
    Variable var expanded, starting from offset pos.

    So if "$@" == "4 my commit message", then:
    "${@:1}" == " my commit message"
    "${@:2}" == "my commit message"
    As you are concatenating ${@:1} ${@:2} you are seeing my commit message twice.