git - 如何使用带参数的嵌套命令创建 Git 别名?

标签 git shell

在我的点文件中,我有以下功能可以工作:

function undelete {
  git checkout $(git rev-list -n 1 HEAD -- "$1")^ -- "$1"
}

...我是这样使用的:
$ undelete /path/to/deleted/file.txt

我想限定这个命令的范围,因为它是一个 git 命令。

如何创建 git 别名以便我可以使用此 git alias 命令?
$ git undelete /path/to/deleted/file.txt

这里有两个,我的尝试不起作用:
git config --global alias.undelete "!f() { git checkout $(git rev-list -n 1 HEAD -- $1)^ -- $1; }; f"
git config --global alias.undelete "!sh -c 'git checkout $(git rev-list -n 1 HEAD -- $1)^ -- $1' -"

最佳答案

可以使用别名来做到这一点(请参阅 jthill's comment ):

git config --global alias.undelete '!f() { git checkout $(git rev-list -n 1 HEAD -- $1)^ -- $1; }; f'
git config --global alias.undelete '!sh -c "git checkout $(git rev-list -n 1 HEAD -- $1)^ -- $1" -'

我建议将任何复杂的东西写成一个 shell 脚本:
#! /bin/sh
#
# git-undelete: find path in recent history and extract
. git-sh-setup # see $(git --exec-path)/git-sh-setup

... more stuff here if/as appropriate ...
for path do
    rev=$(git rev-list -n 1 HEAD -- "$path") || exit 1
    git checkout ${rev}^ -- "$path" || exit 1
done

(for 循环旨在使其允许多个路径名“取消删除”)。

为脚本命名 git-undelete ,放入您的 $PATH (我将脚本放在 $HOME/scripts 中),并且任何时候运行 git undelete , Git 会找到你的 git-undelete脚本并运行它(将 $PATH 修改为在前面有 git --exec-path,以便 . git-sh-setup 工作)。

关于git - 如何使用带参数的嵌套命令创建 Git 别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43880999/

相关文章:

java - 为什么新版本的 EGIT(3.3.x) 在我的系统和 eclipse 上出现错误?

arrays - Bash/Shell 数组中的分隔符

linux - 为几个用户验证 "su"的 Bash 脚本

bash - 如何在 shell 中使用 curl 检查内容类型

angularjs - 如何将 MEAN Stack 部署到 Web 主机

git - 如何在 Git 中记录 Web 项目的发布历史?

git - 仅使用我的提交创建分支/pull 请求

java - 直接运行 shell 命令和从 shell 脚本 sh 文件运行的区别

linux - 根据 bash 中文件名的子字符串复制最新更新的文件

git - merge 分支而不丢失文件