I'm attempting to implement Handyman5's gist (which is a comment on this answer, in this question) as a bash function in my .bashrc file.
:<<COMMENT
Searches all commits in the current git repository for a file that matches a regular expression.
Usage: gitf <regex>
Parameter is required, and must be at least one non-whitespace character.
Based on the GitHub gist
- https://gist.github.com/anonymous/62d981890eccb48a99dc
written by Stack Overflow user Handyman5
- https://stackoverflow.com/users/459089/handyman5
which is based on this SO question:
- https://stackoverflow.com/questions/372506/how-can-i-search-git-branches-for-a-file-or-directory/372654#372654
Short description: Stored in GITF_DESC
COMMENT
#GITF_DESC: For "aliaf" command (with an 'f'). Must end with a newline.
GITF_DESC="gitf [searchterm]: Searches the current git repository for the file name that matches a regular expression.\n"
The function body:
gitf() {
set +x
#Exit if no parameter is provided (if it's the empty string)
param=$(echo "$1" | trim)
echo "$param"
if [ -z "$param" ] #http://tldp.org/LDP/abs/html/comparison-ops.html
then
echo "Required parameter missing. Cancelled"; return
fi
wasFound="0";
LOC=refs/remotes/origin # to search local branches only: 'refs/heads'
ref="%(refname)"
for branch in `git for-each-ref --format="$ref" $LOC`; do
found=$(git ls-tree -r --name-only $branch | grep "$param")
if [ $? -eq 0 ]; then
echo "${branch#$LOC/}: $ref:"; echo " $found"
wasFound="1";
fi
done
if ["$wasFound" -eq 0]; then
echo "No files in this repository match '$param'."
fi
set -x
}
I'm trying to get it to print out the commit it's in, so I can quickly check it out. But it's only printing out the file path, despite the echos. Any guidance to what I'm missing?
Current output for gitf "05"
:
$ gitf "05"
+ gitf 05
+ set +x
05
master:
non_django_files/wordpress_posts/build_java/BuildPart05.java
non_django_files/wordpress_posts/templates/05_login_remember_me.html
[1: command not found
++ history -a
I'm pretty sure the last two lines are an unrelated .bashrc or .inputrc issue, but I'm including them in case they're relevant.
@SwankSwashbucklers: Thank you for basically doing my work for me (I'm new to both Bash and Git, so I say that genuinely). The output is now very clear and useful. I do notice that it's missing some hits. Here is a small repository (2mb zip) for instance. Searching for "05" responds with
$ gitf 05
05
master: 14e5cdd:
non_django_files/wordpress_posts/build_java/BuildPart05.java
non_django_files/wordpress_posts/templates/05_login_remember_me.html
master: 2efdeb1:
non_django_files/wordpress_posts/build_java/BuildPart05.java
non_django_files/wordpress_posts/templates/05_login_remember_me.html
These two commits are the most recent two if that means anything. 05_login_remember_me.html
also exists in at least f87540e
(the very first commit), 3a7dac9
, and 3c5e4ec
.