Browse topics

git init and git clone

Version
2.51
Review
Draft

Summary#

git init creates an empty repository, and git clone copies an existing one, usually names the remote origin and checks out its default branch when one is available. Use --bare for a repository without a working tree, such as a shared push target, and --depth to truncate the history you download.

Syntax#

sh
git init -b main project
git init --bare shared.git
git clone URL directory
git clone --depth 1 URL directory

Example#

sh
(
  set -eu
  scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
  trap 'rm -rf -- "$scratch"' EXIT
  unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
  export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
  export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
  export GIT_PAGER=cat GIT_EDITOR=true

  git init -q -b trunk "$scratch/source"
  cd "$scratch/source"
  git config user.name "Reference Example"
  git config user.email example@example.invalid
  printf 'Demo project\n' > README.md
  git add README.md
  git commit -qm "Add readme"
  git commit -qm "Record review" --allow-empty

  git clone -q "$scratch/source" "$scratch/full"
  cd "$scratch/full"
  git branch --show-current
  git remote
  cat README.md
  echo "full clone commits: $(git rev-list --count HEAD)"

  git clone -q --depth 1 "file://$scratch/source" "$scratch/shallow"
  cd "$scratch/shallow"
  echo "depth 1 commits: $(git rev-list --count HEAD)"
  echo "shallow: $(git rev-parse --is-shallow-repository)"
)

Expected output#

Text
trunk
origin
Demo project
full clone commits: 2
depth 1 commits: 1
shallow: true

Common mistakes#

--depth is ignored when you clone a plain local path: Git warns and copies the full history. Use a file:// URL for a shallow clone of a repository on disk. A depth-limited clone also fetches a single branch unless you add --no-single-branch.

Version applicability#

Git 2.15 added the example's --is-shallow-repository check. Git 2.28 made the name of the first branch configurable through init.defaultBranch, and its manual documents --initial-branch, or -b. On the 2.51 line the built-in default is still master unless configuration or a distribution changes it, so name the branch when a script depends on it.

The complete example requires Git 2.28 or later for git init -b.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0