Search code examples
bashsh

Shell script to split a url and extract the variables


I have a string like this "git@github.com:myOrg/my-repo.git", I am trying to split the url string and get the substrings "myOrg" and "my-repo".

I tried below script but it is failing


REPO=$(echo $SSH_URL | sed  -n 's#.*:\\(.*\\)/.*#\\1#p')

GIT_ORG=$(echo $SSH_URL | sed -n 's/^.*:\\([^\\/]*\\)\\/\\(.*\\)\\.git$/\\1/p')

but I am getting below error

sed: -e expression #1, char 39: unknown option to s

can someone please help


Solution

  • You could use parameter expansion to cut off the unneeded parts:

    url="${SSH_URL}"   # make a copy
    url="${url#*:}"    # drop until colon
    url="${url%.git}"  # drop extension
    
    owner="${url%/*}"  # extract "myOrg"
    repo="${url#*/}"   # extract "my-repo"