7

If I clone a git repository like this

git clone <some-repository>

git creates a directory, named as the 'humanish' part of the source repository. (according to the man page).

Now I want to create a bash script that clones a repository, 'cds' into the newly created directory, and does some stuff. Is there an easy way for the bash script to know the name of the created directory, without explicitly providing a directory to the 'git clone' command?

johanv
  • 962
  • 8
  • 11

2 Answers2

5

To add to Hiery's answer, you will find a complete shell script example in the git repo itself:
contrib/examples/git-clone.sh, with the relevant extract:

# Decide the directory name of the new repository
if test -n "$2"
then
    dir="$2"
    test $# = 2 || die "excess parameter to git-clone"
else
    # Derive one from the repository name
    # Try using "humanish" part of source repo if user didn't specify one
    if test -f "$repo"
    then
        # Cloning from a bundle
        dir=$(echo "$repo" | sed -e 's|/*\.bundle$||' -e 's|.*/||g')
    else
        dir=$(echo "$repo" |
            sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g')
    fi
fi

Note that it takes into account cloning a bundle (which is a repo as one file, useful when working with a repository in the cloud).

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
0

You need to get the url and parse it to get the latest part and strip off the .git.

#!/bin/bash
URL=$1

# Strip off everything from the beginning up to and including the last slash
REPO_DIR=${URL##*/}
# Strip off the .git part from the end of the REPO_DIR
REPO_DIR=${REPO_DIR%%.git}

git clone $URL
cd $REPO_DIR
....
Hiery Nomus
  • 17,429
  • 2
  • 41
  • 37