1

This is probably a dumb mistake. I am using this as a basis for a bash function to try to create a bash script for this git function:

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
}

When I try to source this, it actually is trying to execute the commands - and then gives a syntax error because of this.

I am able to execute the commands locally, so clearly I am missing something obvious in creating my function here.

Community
  • 1
  • 1
enderland
  • 13,825
  • 17
  • 98
  • 152
  • In your else clause, that single quote in front of the git command should be a back tick: `k in 'git` becomes `k in \`git`. – bishop Mar 14 '16 at 15:09
  • @bishop changing that results in the same results. – enderland Mar 14 '16 at 15:11
  • 1
    `command` has a usage of `command [-pVv] command [arg ...]`. That's not what a `for` loop will give you. Do you want to run a command multiple times? If so, put `command` inside of the `for`. As a suggestion, remove "command" and see what happens. – bishop Mar 14 '16 at 15:13
  • [Don't use `for` to iterate over the lines of a stream](http://mywiki.wooledge.org/BashFAQ/001) – glenn jackman Mar 14 '16 at 15:24
  • @glennjackman I was blatantly copying, err, borrowing the script in the other SO answer as the basis for this :-) – enderland Mar 14 '16 at 15:30

1 Answers1

0

After some simplification and removal of the spurious 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
}
bishop
  • 37,830
  • 11
  • 104
  • 139
  • I'd suggest `printf "%s\t%s\n" "$(git show ...)" "$k"` – glenn jackman Mar 14 '16 at 15:25
  • Gave me enough basis to figure out what I needed to do, thanks (I edited it to include my working function)! – enderland Mar 14 '16 at 15:38
  • You're welcome. I made similar edits, refactoring to a version that is more performant per @glennjackman note about `for` iteration. Bonus, use `branch_format $branch_name` to get a formatted version independent of use in `branch`. – bishop Mar 14 '16 at 15:58
  • @glennjackman I can't get `printf '%b'` to work with the escape sequences from `git`. – bishop Mar 14 '16 at 16:09