1

I'm looking for a bash script to generate a GitHub link to a file from the filename in my local checkout.

So if this script existed and was named github-link-for-file, it might work like this:

$ git clone [email protected]:torvalds/linux.git
$ cd linux
$ github-link-for-file include/math-emu/quad.h
https://github.com/torvalds/linux/blob/master/include/math-emu/quad.h

I expect that such a script already exists, but I can't find it. Can anyone else?

(If not, maybe I should write it and add it to a project like https://hub.github.com/. It looks like their "git browse" command is very nearly what I want.)

1

2 Answers 2

3

Should be pretty straightforward. Try this:

#!/bin/bash

URL=`git config --get remote.origin.url | sed 's/\.git//g'`
BRANCH=`git rev-parse --abbrev-ref HEAD`
FILE=$1

echo $URL/blob/$BRANCH/$FILE

exit 0

Save that to a Bash script file and remember to set it to executable with chmod +x.

You can then link the script file to an alias or symlink it in your /usr/bin directory. The script works relatively, so you will need to be inside of the repo directory when you run it.

3
  • That doesn't work, see the example given in the question. The GitHub URL for viewing a file starts "https://" and includes github-specific items like "/blob/". Your script gives "git:" urls and doesn't have "/blob/".
    – Rich
    Commented Dec 18, 2016 at 21:29
  • I believe the URL is based on how the repo was cloned, via SSH or HTTPS. I've tweaked the script to clean up the URL and also incorporate the branch name.
    – Gsinti
    Commented Dec 19, 2016 at 7:10
  • I usually clone via git:, not https:; I have clarified the question. I was really looking for a link to an existing project which did this, rather than a pair programming session to write and debug one. As I hinted in the question, I could write this for myself, but I'd prefer to grab one that works in all the edge cases I haven't thought of yet, like different origin URL forms.
    – Rich
    Commented Dec 19, 2016 at 15:51
0

An alternative to Gsinti's answer which supports remotes that are checked out via SSH

#!/bin/bash

GIT_URL=$(git config --local remote.origin.url | cut -d "@" -f 2 | cut -d "." -f "1-2" | sed "s/:/\//")
URL="https://${GIT_URL}"
BRANCH=`git rev-parse --abbrev-ref HEAD`
FILE=$1

echo $URL/blob/$BRANCH/$FILE

exit 0
1
  • Thanks. I have the same comment that I put on Gsinti's answer: As I hinted in the question, I could write this for myself, but I'd prefer to grab one from a library that works in all the edge cases I haven't thought of yet, like different origin URL forms.
    – Rich
    Commented Aug 22, 2022 at 20:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .