【问题标题】:Bash scripting git branch listsBash 脚本 git 分支列表
【发布时间】:2016-06-29 16:49:42
【问题描述】:

这可能是一个愚蠢的错误。我正在使用this as a basis for a bash function 尝试为this git function 创建一个bash 脚本:

branch() {
   if [[ $@ == "-r" ]]; then
       command for k in `git branch -r | perl -pe 's/^..(.*?)( ->.*)?$/\1/'`; do echo -e `git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k -- | head -n 1`\\t$k; done | sort -r

else
      command for k in `git branch | perl -pe s/^..//`; do echo -e `git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k -- | head -n 1`\\t$k; done | sort -r

   fi
}

当我尝试获取它时,它实际上是在尝试执行命令 - 然后因此给出语法错误。

我能够在本地执行命令,所以很明显我在这里创建函数时遗漏了一些明显的东西。

【问题讨论】:

  • 在 else 子句中,git 命令前面的单引号应该是反引号:k in 'git 变为 k in `git。
  • @bishop 更改会产生相同的结果。
  • command 的用法为 command [-pVv] command [arg ...]。这不是for 循环给你的。你想多次运行一个命令吗?如果是这样,请将command 放在for 内。作为建议,删除“命令”,看看会发生什么。
  • @glennjackman 我公然复制,错误,借用另一个 SO 答案中的脚本作为此的基础:-)

标签: git macos bash


【解决方案1】:

经过一些简化和去除虚假的command:

branch() {
   local options=""
   local pattern="s/^..//"
   if [[ $@ == "-r" ]]; then
      options="-r"
      pattern="s/^..(.*?)( ->.*)?$/\1/"
   fi
   git branch $options | perl -pe "$pattern" | while IFS= read -r k; do
      branch_format $k
   done | sort -r
}
branch_format() {
   echo -e $(git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $1 -- | head -n 1) $1
}

【讨论】:

  • 我建议printf "%s\t%s\n" "$(git show ...)" "$k"
  • 给了我足够的基础来弄清楚我需要做什么,谢谢(我对其进行了编辑以包含我的工作功能)!
  • 不客气。我进行了类似的编辑,根据@glennjackman 关于for 迭代的注释,重构为性能更高的版本。奖励,使用branch_format $branch_name 获得一个独立于branch 使用的格式化版本。
  • @glennjackman 我无法让printf '%b' 处理来自git 的转义序列。
猜你喜欢
  • 2013-01-02
  • 2017-02-09
  • 2017-10-09
  • 2011-04-20
  • 1970-01-01
  • 2019-05-23
  • 2012-01-18
  • 1970-01-01
  • 2015-10-31
相关资源
最近更新 更多