Skip to content

How to Link to Specific Lines of Code on GitHub

A few weeks ago, I noticed a nice feature of GitHub: we can create links to code on GitHub and highlight the lines we talk about. I find this a great help and show you in this post how to do it.

We need to go to the file we want to link to on GitHub and find the line we are interested in. We then can append #L[LineNumber] to the link in the browser. To highlight line 22 for the file Program.cs, we can create this link:

https://github.com/jgraber/Blog_Snippets/blob/main/DbUp/DBMigration/DBMigration/Program.cs#L22

If we open the link in the browser, it should direct us to that file on GitHub and highlight line 22:

Line 22 of the file is marked in yellow.

If we want to highlight a block of code, we can use the approach above and append -L[LineNumberEnd] at the end. To highlight lines 20 to 25 in the Program.cs file, we can use this link:

https://github.com/jgraber/Blog_Snippets/blob/main/DbUp/DBMigration/DBMigration/Program.cs#L20-L25

This highlights the code block between lines 20 and 25:

Lines 20 up and including 25 are now yellow.

Code can change, and so will the highlighted parts with the links above. If we want to make sure that the code stays the same, we need to link to a specific commit. We can put the commit hash (or just the first 7 characters) at the place where main was and create this link:

https://github.com/jgraber/Blog_Snippets/blob/d618b91/DbUp/DBMigration/DBMigration/Program.cs#L20-L25

This highlights the code block between lines 20 and 25, but it will stay the same even if a new commit changes this file:

Lines 20 up and including 25 are now yellow.

Conclusion

This neat feature is a great help when you want to link to code on GitHub. Especially with larger files is it a massive benefit to see what you are talking about without to search for the code in question. And the best part: it is not much extra work in the first place.