CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingMedium
A developer needs to clone a Git repository from a private server and then immediately switch to a specific branch named `feature/new-api`. Which sequence of Git commands will accomplish this efficiently?
- A`git pull ssh://git.example.com/repo.git && git branch feature/new-api`
- B`git clone -b feature/new-api ssh://git.example.com/repo.git`
- C`git clone ssh://git.example.com/repo.git && git checkout feature/new-api`
- D`git init && git remote add origin ssh://git.example.com/repo.git && git fetch origin feature/new-api`
Show answer & explanationAnswer & explanation
Correct answer: B. `git clone -b feature/new-api ssh://git.example.com/repo.git`
The `git clone -b <branch_name>` command allows you to clone a repository and immediately check out a specific branch other than the default (`main` or `master`). This is the most efficient single command to achieve both cloning and switching to the desired branch.
Why the other options are wrong
- A. `git pull` is used to fetch and integrate changes from a remote, not to clone a new repository. `git branch` creates a local branch but doesn't connect it to a remote or check it out.
- C. This works but is less efficient as it first clones the default branch, then requires a separate `git checkout` command to switch. The `-b` option combines these.
- D. This sequence initializes an empty repository, adds a remote, and fetches the branch, but it doesn't automatically check out the `feature/new-api` branch into the working directory; it only downloads its content.
Git Clone Specific Branch
To clone a Git repository and immediately switch to a branch other than the default, use the `git clone -b <branch_name> <repository_url>` command. This streamlines the process by performing both actions in one step.
- `git clone` copies a repository.
- The `-b` or `--branch` flag specifies the initial branch to check out.
- If `-b` is not used, the default branch (e.g., `main` or `master`) is checked out.
Memory trick: Clone a branch directly, like picking a specific fruit from the tree.