如何将参数从git别名传递到外部脚本

问题描述 投票:2回答:1

我有一个问题从git别名传递参数到外部bash脚本文件。目前,我的bash脚本文件与我的.gitconfig位于同一目录中。我计划在那里移动我所有复杂的!f() { }别名,以避免与所有逃避和没有评论作斗争。

所以我的脚本文件名为.gitconfig.kat.aliases.script,它看起来像这样:

#!/bin/bash

openInBrowser() {
    REPO_URL=$(git config remote.origin.url)

    find="[email protected]:"
    replace="https://bitbucket.org/"

    # Replace SSH with HTTPS prefix
    REPO_URL=$(echo $REPO_URL | sed -e "s%${find}%${replace}%g")
    explorer $REPO_URL

    exit 0;
}

checkoutRemoteBranch() {
    echo "$# Parameters"
    echo $0
    echo $1
    echo $2
    if [ "$#" = 2 ] 
    then
        echo -e "BINGO"
        # git fetch
        # git co -b $2 $1/$2
    else
        echo -e "usage:\tgit co-rb <origin> <branch>"
    fi  
}

配置1

在我的.gitconfig [alias]部分中,我有这个:

co-rb = !bash -c 'source $HOME/.gitconfig.kat.aliases.script && checkoutRemoteBranch \"$@\"'
open = !bash -c 'source $HOME/.gitconfig.kat.aliases.script && openInBrowser'  

我遵循this question's语法来获取外部脚本/函数的别名。然后,我遵循this question's语法将参数传递给函数(上面的别名不传递虚拟参数,如建议的问题,更多信息如下)。

问题是,没有伪参数,当我执行git co-rb origin feature/test时,我得到以下输出:

1 Parameters
origin
feature/test

配置2

如果我在$ @之后定义一个虚拟参数...

co-rb = !bash -c 'source $HOME/.gitconfig.kat.aliases.script && checkoutRemoteBranch \"$@\" x'

输出是:

2 Parameters
origin
feature/test
x

配置3

如果我将伪参数的位置更改为co-rb = !bash -c 'source $HOME/.gitconfig.kat.aliases.script && checkoutRemoteBranch x \"$@\"'

输出是:

2 Parameters
origin
x
feature/test

问题:1。配置1 - 参数计数错误,位置参数偏移-1。 1.配置2 - 参数计数正确,但位置参数偏移-1。 1.配置3 - 参数计数正确,但参数全部搞砸了。 x注入中间,位置不正确1美元。

我应该如何设置我的git别名,以便参数计数正确并且位置1..N是我所期望的?或者我应该更改我的shell脚本,以便每次检查参数计数时,我都会检查'count-1'?

bash git git-alias
1个回答
0
投票
$ bash -c 'echo $@' 1 2 3
2 3

$ bash -c 'echo $0 $@' 1 2 3
1 2 3

也就是说,"$@"传递从1开始的参数,但在这种情况下也有第0个参数。

所以通过$0

co-rb = !bash -c 'source $HOME/.gitconfig.kat.aliases.script && checkoutRemoteBranch "$0" "$@"'

$0没有添加到$@,因为在99个用例中,100个不需要。通常它是shell名称或脚本名称,$@中不需要任何一个。

© www.soinside.com 2019 - 2024. All rights reserved.