创建 git 个别名

Creating git aliases

我正在尝试在 ubuntu

中添加以下别名
alias l=log --pretty=format:"%C(yellow)%h\ %ad%Cred%d\ %Creset%s%Cblue\ [%cn]" --decorate --date=short

$ source ~/.aliases
bash: alias: --decorate: not found
bash: alias: --decorate: not found
bash: alias: --numstat: not found

我可以在外面用这个命令 git

我不太确定为什么?有人能帮我吗?我尝试使用谷歌搜索,但并没有走得太远。我不知道bash那么多。

您应该在 git 别名中设置别名并从命令行使用它

您可以直接编辑配置文件或从 CLI 执行:

Git别名

使用 git config --global alias.<name> 添加 git 别名

git config --global alias.l 'log --pretty=format:"%C(yellow)%h\ %ad%Cred%d\ %Creset%s%Cblue\ [%cn]" --decorate'

现在您应该可以将它用于:git l


Ubuntu别名

如果您想在 Ubuntu 中为您的 shell 添加别名:

alias gitl='git l'

你快到了。您只需要将别名放在正确的文件中即可。因为 Git 不会在您部分输入命令时自动推断出您的命令,所以您可以使用 git config 轻松地为每个命令设置别名,如下所示:

git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status

然后在任何回购中使用别名,如:git cigit cogit brgit st

您还可以通过别名运行 外部命令。在这种情况下,您以 ! 字符开始命令。如果您编写自己的工具来使用 Git 存储库,这将很有用:

git config --global alias.visual '!gitk'

您可能还注意到 config 命令接受多个参数(例如 --global 一个)。如果我们查看文档 man git config:

For writing options: write to global ~/.gitconfig file rather than the repository .git/config, write to $XDG_CONFIG_HOME/git/config file if this file exists and the ~/.gitconfig file doesn’t. For reading options: read only from global ~/.gitconfig and from $XDG_CONFIG_HOME/git/config rather than from all available files. See also the section called “FILES”.

还有--system,写入/etc/gitconfig--local,用于本地repo .git/gitconfig,和--worktree,类似于--local.

但您可以直接编辑文件本身。它看起来类似于:

# in ~/.gitconfig
[alias]
    lg = log --all --stat --pretty=oneline --graph --format='%h %d %an %cr %s' --oneline
    l = log --all --stat --graph --format='%h %d %an %cr %s'
    up = pull --rebase
    br = branch --verbose -a
    sfp = push --force-with-lease

这是一个有点老的问题,但理解和创建 git 别名非常重要,因为这会节省您的大量时间。

在您的问题中,您几乎可以回答一个愚蠢的错误,即您正在尝试使用脚本创建别名。

需要在 .gitconfig 文件中定义别名。不仅是 alias,还有所有配置部分,例如

[core][color][pack][help][alias]

我想与您分享一些基本且有用的别名,以备不时之需,您可以根据自己的需要和日常使用情况进一步更改

[alias]
    lg = log -p
    lol = log --graph --decorate --pretty=oneline --abbrev-commit
    lola = log --graph --decorate --pretty=oneline --abbrev-commit --all
    st = status
    co = checkout
    ci = commit -a -m
    br = branch
    ls = ls-files
    po = push origin
    f = fetch
    p = pull
    delete = branch -d master
    com = checkout master
    cob = checkout -b
    unstage = reset HEAD
    url = remote set-url origin 
    ign = ls-files -o -i --exclude-standard
    cp = cherry-pick

您还可以为多个 git 命令的组合创建一个别名,例如:

rdev = !git checkout dev && git pull && git checkout - && git rebase dev

如果需要任何其他理解,请告诉我。