iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
✨

Getting Started with Git (for Ubuntu)

に公開
2022/04/05

This article briefly explains how to install Git and the GitHub CLI on Ubuntu and introduces settings for utilizing useful features such as command completion. It also touches upon the initial configuration of Git.

0. Preparing Ubuntu

Please prepare an Ubuntu environment somehow. Having a physical machine is reassuring, but a virtual machine or Windows Subsystem for Linux (WSL) is also fine.

The following explanations assume that you are using Ubuntu. Furthermore, it assumes that you are using Bash as your shell.

1. Installing Git

Git is a free and open-source distributed version control tool. It is designed to handle everything from small to very large projects with speed and efficiency.

You can use apt(8) or apt-get(8) to install Git on Ubuntu. However, the version of Git provided by Ubuntu might be behind the latest version.

To install the latest version of Git on Ubuntu, you need to either build it from source or obtain the package from the official Git Personal Package Archive (PPA). Here, I will introduce how to install it via PPA.

Execute the following commands:

Installing Git
$ sudo add-apt-repository ppa:git-core/ppa
$ sudo apt update
$ sudo apt upgrade
$ sudo apt install git

To verify that the installation of Git is complete, let's display the version of Git.

Displaying the Git version
$ git --version
git version 2.20.1

2. Installing GitHub CLI

GitHub CLI is a tool for performing various GitHub functions (such as creating repositories or managing Gists) from the command line.

While you can use apt(8) or apt-get(8) to install the GitHub CLI, this will result in a version that is significantly behind the latest release. You can also install it using snap(1), but GitHub does not recommend this (do not use).

The method introduced by GitHub is as follows:

Installing GitHub CLI
$ curl -fsSL \
> https://cli.github.com/packages/githubcli-archive-keyring.gpg \
> | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
$ echo "deb [arch=$(dpkg --print-architecture) \
> signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] \
> https://cli.github.com/packages stable main" \
> | sudo tee /etc/apt/sources.list.d/github-cli.list >/dev/null
$ sudo apt update
$ sudo apt upgrade
$ sudo apt install gh

To verify that the installation of the GitHub CLI is complete, let's display the version of the GitHub CLI.

Displaying the GitHub CLI version
$ gh --version
gh version 2.4.0 (2021-12-21)
https://github.com/cli/cli/releases/tag/v2.4.0

3. Configuring Command Completion for GitHub CLI

GitHub CLI has many subcommands. Since it's difficult to remember all of them, having command completion is convenient.

Add the following content to ~/.bash_aliases (create it if it doesn't exist). To handle cases where the gh command might not exist, we check for the existence of the gh command with an if statement before configuring command completion.

~/.bash_aliases (Add)
if which gh >/dev/null
then
	eval "$(gh completion -s bash)"
fi

Once editing is complete, apply the settings. The easiest way is to log out and log back in. Alternatively, you can apply them by running exec $SHELL.

~/.bash_aliases is a file called from ~/.bashrc. ~/.bashrc is called when the shell starts, and its contents are executed (in the case of a login shell, it is called from ~/.profile or ~/.bash_profile). If there is an error in the settings written to these files, there is a risk of being unable to log in in the worst-case scenario. After editing these files, please try logging in from another terminal to confirm there are no errors in the settings.

Completion functions can be used by pressing the [Tab] key multiple times.

Trying out completion ([Tab] indicates pressing the [Tab] key)
$ gh a[Tab][Tab]
alias       (Create command shortcuts)
api         (Make an authenticated GitHub API request)
auth        (Login, logout, and refresh your authentication)
$ gh alias [Tab][Tab]
delete  (Delete an alias)
list    (List your aliases)
set     (Create a shortcut for a gh command)

4. Configuring Command and Option Completion for Git

Git also has many subcommands and options. Since it's difficult to remember all of them, having completion for commands and options is convenient.

A script that provides completion functionality for Git commands and options is provided by Git. First, retrieve it.

Retrieve the script
$ curl -o $HOME/.git-completion.bash \
> https://raw.githubusercontent.com/git/git\
> /master/contrib/completion/git-completion.bash

Then, configure it to be loaded when the shell starts. Add the following content to ~/.bash_aliases.

~/.bash_aliases (Add)
if [ -e $HOME/.git-completion.bash ]
then
	source $HOME/.git-completion.bash
fi

Completion becomes available once the settings are applied.

Trying out completion ([Tab] indicates pressing the [Tab] key)
$ git a[Tab][Tab]
add       am        apply     archive   
$ git branch [Tab][Tab]
FETCH_HEAD       ORIG_HEAD        main             origin/develop 
HEAD             develop          origin/HEAD      origin/main 

5. Displaying Git Information in the Prompt

When using Git, you may want to check the current status of the repository. It can be convenient to have repository information displayed in the shell prompt.

Git provides a script for displaying the repository's current information in the prompt. First, retrieve it.

Retrieve the script
$ curl -o $HOME/.git-prompt.sh \
> https://raw.githubusercontent.com/git/git\
> /master/contrib/completion/git-prompt.sh

Then, configure it to be loaded when the shell starts. At the same time, configure settings such as the items to be displayed. Add the following content to ~/.bash_aliases.

~/.bash_aliases (Add)
if [ -e $HOME/.git-prompt.sh ]
then
	# Please comment out items you don't need
	# Or leave the right side empty, like HOGE=
	GIT_PS1_SHOWDIRTYSTATE=true
	GIT_PS1_SHOWUNTRACKEDFILES=true
	GIT_PS1_SHOWSTASHSTATE=true
	GIT_PS1_SHOWUPSTREAM=auto

	source $HOME/.git-prompt.sh
	PS1='\u@\h:\w$(__git_ps1) \$'	# This setting is very plain
fi

I will briefly explain the settings for each variable. Detailed explanations are provided as comments within the script.

GIT_PS1_SHOWDIRTYSTATE

If you set a value for this variable, it will display * when there are unstaged changes and + when there are staged but uncommitted changes.

user@host:~/foo (main) $ vi README
user@host:~/foo (main*) $ git add README	# Unstaged changes
user@host:~/foo (main+) $ git commit		# Staged and uncommitted changes
user@host:~/foo (main) $ 

GIT_PS1_SHOWUNTRACKEDFILES

If you set a value for this variable, it will display % when there are untracked (new) files.

user@host:~/foo (main) $ touch NEWFILE
user@host:~/foo (main%) $ git add NEWFILW	# There are untracked files
user@host:~/foo (main+) $ 			# Tracked (staged)

GIT_PS1_SHOWSTASHSTATE

If you set a value for this variable, it will display $ when there are stashed changes.

user@host:~/foo (main) $ vi README
user@host:~/foo (main*) $ git stash push README		# Unstaged changes
user@host:~/foo (main$) $ 				# Stashed

GIT_PS1_SHOWUPSTREAM

If you set the value auto for this variable, it will display the status relative to the upstream.

user@host:~/foo (main=) $ git fetch origin
user@host:~/foo (main<) $ git merge origin/main		# Behind upstream
user@host:~/foo (main=) $ vi SOMEFILE			# Caught up with upstream
user@host:~/foo (main *=) $ git add SOMEFILE
user@host:~/foo (main +=) $ git commit
user@host:~/foo (main>) $ git fetch origin		# Ahead of upstream
user@host:~/foo (main<>) $				# Diverged from upstream

The content to be displayed in the prompt is defined in the shell variable PS1. For details, refer to the Bash manual.

6. Git Configuration

When starting with Git, you need to perform some initial configuration.

6.1. Name and Email Address

You need to set your name and email address. The information set here will be made public along with your commit contents.

If you want to keep your email address private, it is a good idea to use the email address in the format 01234567+UserName@users.noreply.github.com (red underline in the figure below) shown in the "Primary email address" section at https://github.com/settings/emails.

Execute as follows:

$ git config --global user.name 'UserName'
$ git config --global user.email 'mail@example.com'

6.2. Default Branch Name

Conventionally, master has been used as the default branch name. However, there has been a movement to change this because the term master is considered sensitive as it evokes the term slave. The term proposed instead of master is main. Currently, GitHub uses main as the default branch name by default unless otherwise specified.

To set the default branch name of Git to main, execute the following:

$ git config --global init.defaultbranch 'main'

6.3. Default Editor

Git uses an editor for various tasks, such as writing commit messages. If you have a preferred editor, setting it up will make your experience more pleasant.

To set the editor used by Git to vi, execute the following:

$ git config --global core.editor 'vi'

6.4. Verifying Settings

Various Git settings are stored in ~/.gitconfig. Repository-specific settings are stored in .git/config.

To verify the current settings from the command line, execute the following:

$ git config --list

Conclusion

That's all.

Bonus: Colorful PS1 Shell Variable for xterm

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(__git_ps1)\[\033[00m\] \$ '
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"

References

Discussion