How to copy the remote repository URL?
- 2 Min. Read.
You might find yourself often in a situation where you want to copy the remote repository URL through a single command. Let’s tackle this problem heads on:
Getting a list of remotes
We can get a list of remotes by typing in the following command:
1 |
git remote -v |
This will get you output like this:
1 2 |
origin git@bitbucket.org:username/repository.git (fetch) origin git@bitbucket.org:username/repository.git (push) |
Isolating the fetch URL
The next thing we have to do is isolate the fetch URL using awk:
1 |
git remote -v | awk '/fetch/{print $2; exit;}' |
This will get you output like this:
1 |
git@bitbucket.org:username/repository.git |
Awk will scan for lines containing ‘fetch’ and then output the second part of that match. Parts are by default separated by whitespace.
From the manpage:
An input line is normally made up of fields separated by white space, or by regular expression FS. The fields are denoted $1, $2, …, while $0 refers to the entire line. If FS is null, the input line is split into one field per character.
We exit after printing the first matched line, so we can isolate the first URL (if you have multiple remotes).
If you wanted to get the push URL, you can replace /fetch/{print $2; exit;}
by /push/{print $2; exit;}
Copying the result to your keyboard
Last thing to do is to copy this result to the keyboard using pbcopy:
1 |
git remote -v | awk '/fetch/{print $2; exit;}' | pbcopy |
Now your clipboard contains the fetch URL of your remote, but you might notice that there’s an annoying newline at the end, let’s trim that away using tr:
1 |
git remote -v | awk '/fetch/{print $2; exit;}' | tr -d '\n' | pbcopy |
And there you have it, put that command in an alias and you’ll never worry again about copying the remote URL from the repository.