The idea here is to change remotes from http to ssh in all git repositories

find / -type d -name '.git' 2>/dev/null | xargs -I {} $SHELL -c \
'cd $(dirname {}) && echo $(pwd) > /tmp/log.log && git remote | \
perl -ne "if (`git config --get remote.$_.url` =~ m#https://(.*)/(username.*)#){`git remote remove $_ && git remote add $_ git\@$1:$2`}"

What I want to do is to find all my (hense username in perl regex) repositories and switch them to use ssh instead of http. I've tested perl script, it's working properly, but when I use it in command it outputs this

fatal: No such remote: remote syntax error at -e line 1, near "( =~" syntax error at -e line 1, near ";}" Execution of -e aborted due to compilation errors. xargs: /bin/zsh: exited with status 255; aborting


I'm not exactly sure what you want (what the exact expected command is), but this:

printf "%s\n" 'https://github.com/username/reponame.git' \
 'git@github.com:username/reponame' | perl -lne \
'if (m#https://(.*?)/(.*/)#) {print "git remote remove $_ && git remote add $_ git\@$1:$2"}'

should print

git remote remove https://github.com/username/reponame.git && git remote add https://github.com/username/reponame.git git@github.com:username/

(Change the print to system if you're sure you want to run the commands)

I changed the for r in xyz to input the URL:s to Perl's stdin, if you want to give them on the command line, you could do something like

perl -le '$_=shift; if (m#http://(.*?)/(.*/)#) {print "blah $_ $1:$2"}' http://foo.bar/user/something

to drop the command line argument to $_ (which is implicitly used by m// unless you specify something else with $var =~ m//).

Also, better escape the @ in the string, as it's the sigil for an array variable.

  • okay, so i'm actually need git remote | some perl code that will do the work. I'm trying $remote = qx(git config --get remote.$_.url); print $remote; } but this isn't working Dec 15 '16 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.