Linux & Bash: Git hosting with SSH

In this blog post, I'll guide you through setting up a Git remote repository in a Linux server. This guide assumes that you have SSH set up, and understand the basics of Git.

Git remotes are just minimal Git repositories without the working tree. The working tree enables you to edit the files within the repository, while the actual revision history is hidden in the .git folder. Minimal Git repositories, formally called bare repositories, are created as so:

mkdir ~/magician.git  
cd ~/magician.git  
git init --bare  

You can have a look at the contents of the bare repository:

user@hostname:~/magician.git$ ls  
HEAD        description info        refs  
config      hooks       objects  

Bare repositories are useless on their own. You have to clone them to make them useful:

cd ~  
git clone ~/magician.git  
cd magician  

Now you can make changes to your repository. For now let's just create the file hello-world.txt:

touch hello-world.txt  
git add hello-world.txt  
git commit -m "Added first file"  
git push origin master  

Now, if you were to share your bare repository at ~/magician.git with someone else (maybe via a flash drive), he can clone the repository and make changes at the same time as you. To merge your commits with his, he could push to the repository, share it back with you and then you could pull and push to merge the changes.

Instead of relying on passing flash drives around, you could have your friend SSH into a server that hosts the Git repository, similar to Github, except locally.

Since you already have the bare repository at ~/magician.git, cloning it over SSH is easy!

git clone user@hostname:~/magician.git  

user would be your username and hostname the IP address of the machine that hosts your Git repository. If you are using port forwarding with VirtualBox, the following command would specify the SSH port to use when cloning:

git clone ssh://user@hostname:1022/~/magician.git  

As long as someone has access to the same user on the machine, he can clone the repository. If you do not want the people you are sharing your repository to have access to your other personal files, you could create a user account just for Git repository hosting, or move to an advanced solution like GitLab, which serves as your own personal GitHub.