interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / Documentation / gittutorial.adoc

798 lines · 28405 bytes Raw Blame History
1gittutorial(7)
2==============
3
4NAME
5----
6gittutorial - Introduction to Git for beginners
7
8DESCRIPTION
9-----------
10
11Git is a program that lets you collaborate with others on code, back up
12your code, roll back to an earlier version of your project, track how
13your project has changed over time, and much more.
14
15This tutorial explains how to create a new Git project, make
16changes to it, and upload the project to the Internet. It usually takes
17less than an hour if you have a little previous experience with Git, and
181-2 hours if not.
19
20We'll show you how to use the commands `git commit`, `git add`,
21`git diff`, `git status`, and `git push`.
22
23What we'll be doing
24-------------------
25
26Git lets you take snapshots of your code, like a checkpoint in a video
27game. These snapshots are called "commits". Which files to save in a
28commit is up to you.
29
30When Git stores a commit, it stores a copy of every file in the commit
31in a database in a folder called `.git`. This is called a "Git repository".
32
33In this tutorial we're going to show you how to:
34
351. Create a Git repository in a folder with the command `git init`.
36 This creates the `.git` folder where Git stores all your commits.
372. Tell Git which files you want to put in a commit
383. Make a commit
394. Change a file and make a new commit with the new version
405. Make experimental changes and throw them away
41
42We'll also explain how to use Git to put your code on the Internet.
43
44Command line vs graphical interfaces
45------------------------------------
46
47Git is a command line program, but there are many graphical interfaces
48for Git built by the community. Your text editor might even have a
49built-in Git integration.
50
51In this tutorial, we'll give instructions for using Git from the
52command line. We can't give you instructions for how to do it in your
53graphical interface because there are so many of them.
54
55You can always switch back and forth between using the command line and
56a graphical interface at any time.
57
58Step 1: Make sure Git is installed
59----------------------------------
60
61To do this tutorial, you'll need:
62
631. Git to be installed. You might already have it installed,
64 and if not there are directions at https://git-scm.com/install/
652. A terminal to use. On Windows, you can use Git Bash which comes
66 when you install Git.
67
68You can check if Git is installed by running this in your terminal:
69
70------------------------------------------------
71$ git --version
72------------------------------------------------
73
74It should output something like this:
75
76------------------------------------------------
77git version 2.54.0
78------------------------------------------------
79
80The exact version isn't too important: this tutorial is designed to work
81with any version of Git after 2.23.0.
82
83[[step_2]]
84Step 2: Introduce yourself to Git
85---------------------------------
86
87The first time you use Git on a computer, it's a good idea to tell Git
88your name and public email address. If you don't, you'll get a lot of
89warnings from Git. To do this, run:
90
91------------------------------------------------
92$ git config --global user.name "Namey McName"
93$ git config --global user.email you@example.com
94------------------------------------------------
95
96The name and email is so that other people you're collaborating with
97can know who made the changes. You can set them to anything you want.
98
99To check if the name and email have been set, you can run these
100commands. They should display your name and email:
101
102------------------------------------------------
103$ git config user.name
104$ git config user.email
105------------------------------------------------
106
107Next, configure Git to set the default branch name to `main` (instead
108of `master`) by running this command. We can't explain what a branch is
109yet, but Git is going to
110https://sfconservancy.org/news/2020/jun/23/gitbranchname/[make `main` the default soon],
111and setting this avoids some extremely annoying problems in Step 14.
112
113------------------------------------------------
114$ git config --global init.defaultBranch main
115------------------------------------------------
116
117If there's no output, then it succeeded.
118
119[NOTE]
120It's also possible to set a different email address for every project,
121but we're not covering that here.
122
123Step 3: Create an empty folder and 1 file
124-----------------------------------------
125
126In your terminal, create an empty folder and move into it.
127Later on you could follow the same steps in this tutorial to take an
128existing project and start managing it with Git, but we're going to use
129an empty project so that everyone following this tutorial has the exact
130same files.
131
132For example, run these commands to make a folder called `myproject`:
133
134------------------------------------------------
135$ mkdir myproject
136$ cd myproject
137------------------------------------------------
138
139Next, using your text editor, create a file in this folder, so we
140have something to work with.
141
142Make a file called README.md, with these contents:
143
144------------------------------------------------
145We're doing a Git tutorial!
146We need 2 lines in this file so here's a second one
147------------------------------------------------
148
149Save `README.md` and keep it open in your text editor so you can
150easily edit it later. The exact contents aren't too important, but
151we'll use those contents in the example output later.
152
153You can check that the file is in the right place by running `ls`,
154like this:
155
156------------------------------------------------
157$ ls
158------------------------------------------------
159
160The output should look like this:
161
162------------------------------------------------
163README.md
164------------------------------------------------
165
166Step 4: Create a Git repository
167-------------------------------
168
169A Git repository lets you save snapshots of your code. Every time you make a
170snapshot, Git stores a copy of the contents of every file in the snapshot.
171
172This might feel unbelievable, but Git uses compression so you can easily
173store tens of thousands of snapshots without using too much disk space.
174
175You can create a Git repository for any folder in your computer by
176running the command `git init`.
177
178Run `git init` in the folder you just created, like this:
179
180------------------------------------------------
181$ git init
182------------------------------------------------
183
184Git will reply:
185
186------------------------------------------------
187Initialized empty Git repository in .git/
188------------------------------------------------
189
190You might notice a new hidden folder was created, named `.git`.
191You don't need to use this folder directly in any way, but it's where
192your commits will be stored.
193
194Step 5: Make your first commit
195------------------------------
196
197Next, we're going to take a snapshot of all the files in the directory
198and tell Git to store them. Git calls these snapshots "commits".
199Making a commit in Git is a two step process: first you need to run `git
200add` and then `git commit`.
201
202The reason it's a two step process is that sometimes you might not
203actually want Git to store a commit with _all_ the files in a folder.
204For example, if you're compiling your program to a binary, you might
205want Git to put the program's source code in your commit but not
206compiled binary. You can also use a `.gitignore` file to help with this.
207
208For now, we're going to store a commit with every file in your folder,
209as well as in every subfolder.
210
211The first step of making a commit is to tell Git which files you
212want to include in the commit using `git add`. To tell Git
213"include all files", run this command:
214
215------------------------------------------------
216$ git add .
217------------------------------------------------
218
219To check if it succeeded, you can run `git status`.
220The output should look like this:
221
222
223------------------------------------------------
224$ git status
225On branch main
226
227No commits yet
228
229Changes to be committed:
230 (use "git rm --cached <file>..." to unstage)
231 new file: README.md
232------------------------------------------------
233
234Next you can create the commit using the `git commit` command, like
235this:
236
237------------------------------------------------
238$ git commit -m "Initial commit"
239------------------------------------------------
240
241The `-m` flag stands for "message", and it lets you set a reminder
242for your future self of what you were doing. The message
243("Initial commit" in this example) can say anything you want.
244
245The output should look like this:
246
247------------------------------------------------
248[main (root-commit) 4a7e367] Initial commit
249 1 file changed, 2 insertions(+)
250 create mode 100644 README.md
251------------------------------------------------
252
253You've now stored the first version of your project in Git!
254
255`git status` is very important
256------------------------------
257
258`git status` shows you the current state of your Git repository.
259It can give a huge amount of different information that takes
260practice to interpret, so this tutorial has several examples of
261how to interpret the output of `git status` in different situations.
262
263It's often useful to run `git status` before and after running a Git
264command to see how it changed things.
265
266Step 6: Make a change
267---------------------
268
269Now, let's learn how to make a change to a file and review the change you made.
270In this example, we'll update the file `README.md`, but you can edit a
271different file.
272
273First open `README.md` in your favourite text editor, make a tiny or
274silly change, and save it. In our example, we'll edit the first line to
275add more exclamation marks:
276
277------------------------------------------------
278We're doing a Git tutorial!!!!
279------------------------------------------------
280
281
282Next, in the terminal, run the command `git status` to get a summary of
283what you changed since the last Git commit.
284
285------------------------------------------------
286$ git status
287------------------------------------------------
288
289The output will look something like this:
290
291------------------------------------------------
292On branch main
293
294Changes not staged for commit:
295 (use "git add <file>..." to update what will be committed)
296 (use "git restore <file>..." to discard changes in working directory)
297 modified: README.md
298------------------------------------------------
299
300This output says that we've changed `README.md` since the last time
301we committed.
302
303Next, if you want to see the details of how you've changed `README.md`,
304you can run `git diff`.
305
306------------------------------------------------
307$ git diff
308------------------------------------------------
309
310The output will look something like this:
311
312------------------------------------------------
313diff --git a/README.md b/README.md
314index ffa8b85..a49e4b0 100644
315--- a/README.md
316+++ b/README.md
317@@ -1,2 +1,2 @@
318-We're doing a Git tutorial!
319+We're doing a Git tutorial!!!!
320 We need 2 lines in this file so here's a second one
321------------------------------------------------
322
323This output says that we deleted one line (`We're doing a Git
324tutorial!`) and added one line (`We're doing a Git tutorial!!!!`). By
325default Git will show the lines you removed in red, and the lines you
326added in green. Removed lines start with a minus `-` and added lines
327start with a plus `+`.
328
329Step 7a: Make a second commit
330-----------------------------
331
332Now that we've changed `README.md`, let's make another commit.
333We're going to follow the same steps as before when we made our first
334commit.
335
336First, tell Git that we want to include the new version of `README.md`
337in the next commit:
338
339------------------------------------------------
340$ git add README.md
341------------------------------------------------
342
343and then run `git commit`, like this:
344
345------------------------------------------------
346$ git commit -m "Update README"
347------------------------------------------------
348
349The output should look like this:
350
351------------------------------------------------
352[main 32e0171] Update README
353 1 file changed, 1 insertion(+), 1 deletion(-)
354------------------------------------------------
355
356This says that the new commit is the same as the previous commit,
357except that we changed 1 line of 1 file.
358
359Step 7b: Make a second commit (the short way)
360---------------------------------------------
361
362Instead of running the two commands in Step 7a above, you
363could also run this command as a shortcut. It will:
364
3651. Get a list of every file in the most recent commit
3662. Commit the current version of all of those files
367
368------------------------------------------------
369$ git commit -am "Update README"
370------------------------------------------------
371
372The `-a` stands for "all".
373
374Understanding `git status` output: "untracked files"
375----------------------------------------------------
376
377Now let's talk about a term you'll see in the `git status` output:
378"untracked files".
379
380First create a new file called `example.txt`. It can be empty.
381
382Then run the command `git status`. You should see this output:
383
384----------
385On branch main
386
387Untracked files:
388 (use "git add <file>..." to include in what will be committed)
389 example.txt
390
391nothing added to commit but untracked files present (use "git add" to track)
392----------
393
394This has a list of "untracked files". An untracked file is a file which
395was not part of the latest commit. By default Git will ignore these
396files.
397
398If you want to commit an untracked file, you can add it like this:
399
400----------
401$ git add example.txt
402----------
403
404Then you can run `git commit` to commit it (though see the warning in
405the next section!).
406
407Warning about terminal text editors
408-----------------------------------
409
410If you run `git commit` without any arguments, Git will open a
411text editor in the terminal for you to use to edit your commit message.
412This lets you write a longer commit message with more details.
413By default, Git uses the `vi` text editor, which is extremely difficult
414to use if you're not used to it. On Windows, the Git installer asks you
415to set your text editor during the install to avoid this problem.
416
417Some signs that you're trapped in `vi`: suddenly typing doesn't work
418anymore, and there are tilde `~` characters on the bottom left of the
419screen.
420
421If Git opens `vi` and you'd rather use a different editor, you can
422handle it like this:
423
4241. Quit by pressing the `Escape` key, then typing `:q!` and then `Enter`
4252. Run `git config --global core.editor YOUR_PREFERRED_EDITOR`
426 to configure which editor to use. For example, `nano` is available
427 on a lot of systems and has basic instructions on the screen for how
428 to use it. Here is a list of
429 https://git-scm.com/book/en/v2/Appendix-C:-Git-Commands-Setup-and-Config#ch_core_editor[how to configure some common editors].
4303. Run `git commit` again
431
432If you don't want to set up a text editor yet, you can also just use
433`git commit -m"your message"` like we did earlier in this tutorial.
434
435Step 8: Make a change and throw it away
436---------------------------------------
437
438One of the most useful things about Git is that it lets you safely
439experiment: you never need to be scared to change your code because you
440can always go back to the old version.
441
442Before starting to experiment, run `git status` to check the current
443state of your Git repository:
444
445------------------------------------------------
446$ git status
447On branch main
448
449nothing to commit, working tree clean
450------------------------------------------------
451
452This "working tree clean" message means that there haven't been any
453changes since your last commit.
454
455Now make a change to `README.md`, and run `git status` again. Like last
456time, you should see a message like this:
457
458------------------------------------------------
459$ git status
460On branch main
461
462Changes not staged for commit:
463 (use "git add <file>..." to update what will be committed)
464 (use "git restore <file>..." to discard changes in working directory)
465 modified: README.md
466------------------------------------------------
467
468This tells us that `README.md` has been changed since the last commit.
469But we don't actually want this change, so let's undo it! We can restore
470`README.md` back to how it was at the most recent commit using the `git
471restore` command.
472
473**WARNING**: `git restore` can't be reversed! Any time you run it it's
474important to be absolutely sure that you're okay with throwing away your
475changes since the last commit.
476
477------------------------------------------------
478$ git restore README.md
479------------------------------------------------
480
481Now open `README.md` again. You should see that your changes have been undone.
482
483You can stop here!
484------------------
485
486The commands we've learned so far (`git init`, `git add`, `git commit`,
487`git diff`, `git status`, and `git restore`) are enough to get a lot out
488of Git on their own.
489
490With these commands, you can keep copies of past versions of your code
491on your computer and safely experiment with big changes to your code.
492
493When using Git this way, all of your code just lives on your computer.
494But if you want to put your code on the Internet so that other people
495can use it or back it up, then you'll need to learn about one more
496command: `git push`.
497
498The rest of this tutorial is about how to upload your code to a Git
499repository on the Internet. The high level process is:
500
5011. Create an account on the Git host
5022. Configure Git so that it can login to the Git host to make changes
5033. Run `git push origin main` to upload your code
504
505Navigating the Git host's UI can be tricky, and it's hard for us to
506give you exact directions because the UIs change a lot.
507There's a rich tradition of people learning Git from their "Git friend"
508who already knows Git, and if you have one of those it might be useful
509to ask them if you get stuck. There are many ways to do things in Git,
510so they might suggest a slightly different way.
511There's also a troubleshooting guide at the end with the most common
512issues folks have run into while doing this tutorial.
513
514Step 9: Create an account on a Git host
515---------------------------------------
516
517To put your code on the Internet, you need it to be hosted somewhere.
518The easiest way to do this is to sign up with a Git host. There's a list
519of Git hosts (many of them offer free accounts) at
520https://git-scm.com/tools/hosting. GitHub and GitLab are two popular hosts.
521
522If you're comfortable running a server, there are other ways to host
523a Git repository on the internet, like connecting through SSH or open
524source Git forge software to your server.
525
526Step 10 (Mac/Linux only): Create an SSH key if needed
527-----------------------------------------------------
528For Git to upload changes to another Git repository, it needs a way to
529login to that repository. One of the most popular ways to do this is
530with an SSH key.
531
532On Windows, you can skip this step and the next one because Git for
533Windows comes with
534https://github.com/git-ecosystem/git-credential-manager[Git Credential Manager]
535to handle logging in.
536
537If you don't already have an SSH key, you'll need to create one.
538You can check if you already have an SSH key by running:
539
540-------------------------------------------
541$ ls ~/.ssh/*.pub
542-------------------------------------------
543
544If you don't already have an SSH key, run:
545
546-------------------------------------------
547$ ssh-keygen
548-------------------------------------------
549
550`ssh-keygen` will ask you for some details.
551The easiest way to do this is to just press Enter at every prompt until
552it's done.
553
554NOTE: All of the advice about how to use SSH in this tutorial is aimed
555at getting it to work as quickly as possible. Setting up SSH in a secure
556way is very far outside the scope of this tutorial. If you have a
557security team in your organization, they might have very different
558opinions about the appropriate way to configure authentication with Git.
559
560Step 11 (Mac/Linux only): Tell the Git host your SSH public key
561---------------------------------------------------------------
562
563First, find your SSH key like this:
564
565-------------------------------------------
566$ ls ~/.ssh/*.pub
567-------------------------------------------
568
569That will output something like this. The exact filename depends on the type
570of key. The important thing is that you're looking for a filename that
571ends in `.pub` ("pub" stands for "public"):
572
573-------------------------------------------
574/home/alice/.ssh/id_ed25519.pub
575-------------------------------------------
576
577Copy the contents of that file to your clipboard. One way to do that is
578to run this command (replacing the filename with the right filename),
579and then copy the output.
580
581-------------------------------------------
582cat /home/alice/.ssh/id_ed25519.pub
583-------------------------------------------
584
585Then login to your account on the Git host you chose and paste the SSH
586key into the appropriate place. Depending on the Git host, it's likely
587under "SSH keys" in your settings. If it asks you what type of SSH key,
588look for something like "Authentication Key".
589
590Once you've done this, you're done! Git will automatically use your SSH
591key to try to connect.
592
593[[step_12]]
594Step 12: Create an empty Git repository on the Git host
595-------------------------------------------------------
596
597Go to the Git host's website and create a new Git repository. If there's
598an option to "create a README.md", "add a license", or something
599similar, make sure to say no to all of them.
600
601**WARNING**: If you create a public repository and push your repository
602to it, then your name and email address, as well as the contents of
603any files you committed and every previous version of those files, will
604be on the public internet. Some Git hosts have the option to create
605a private repository instead, to keep your information private.
606
607Step 13: Find the address of the repository
608-------------------------------------------
609
610Now, find the address of the repository on your Git host.
611
612If you followed the Mac/Linux instructions to set up an SSH key, look
613for an "SSH" address like this:
614
615-------------------------------------------
616git@git.example.com:username/repo.git
617-------------------------------------------
618
619If you're on Windows, look for an "HTTPS" address like this:
620
621-------------------------------------------
622https://git.example.com/username/repo.git
623-------------------------------------------
624
625(where `example.com`, `username` and `repo` will be replaced with the
626actual values).
627
628If you can only find an address starting with `https://` and you need
629an SSH address then you can often translate it to the SSH format by
630replacing `https://` with `git@` and replacing the `/` after the domain
631name with an `:`. Here's how:
632
633-------------------------------------------
634https://git.example.com/username/repo
635^^^^^^^^ ^
636replace with "git@" replace with ":"
637-------------------------------------------
638
639[[step_14]]
640Step 14: Push your changes
641--------------------------
642
643Finally, we're ready to send the information in your local Git repository
644to the one on the internet!
645
646First, tell Git about the other repository by running `git remote add`
647in your terminal
648(replace `git@example.com:username/repo.git` with the address from Step 13):
649
650-------------------------------------------
651$ git remote add origin git@example.com:username/repo.git
652-------------------------------------------
653
654This tells Git to save the URL `git@example.com:username/repo.git` in
655your Git repository's configuration under the name `origin`, so that you
656can use it later. If you make a mistake while doing this, you can run
657`git remote remove origin` and try again.
658
659Then tell Git to send the information, with `git push`
660(if this doesn't work, read the "Troubleshooting `git push`" section for advice!):
661
662-------------------------------------------
663$ git push --set-upstream origin main
664-------------------------------------------
665
666On Windows, this should pop up a dialog from Git Credential Manager
667asking you to log in to the Git host in your browser.
668
669Let's break down this `git push` command:
670
671* `origin` refers to the Git repository that we just added with
672 `git remote add` (`git@example.com:username/repo.git`).
673 You can use any name (not just `origin`), but using `origin` often
674 makes things easier because it's the default for `git push` and `git pull`.
675* `main` is the name of your current Git branch.
676 We haven't covered branches yet, but `main` is the default branch name.
677* `--set-upstream` tells Git to make this the default for `git push` for
678 the `main` branch. After you set the upstream, `git status` will
679 also tell you if you have commits that haven't been pushed.
680
681The output should look like this:
682
683-------------------------------------------
684Enumerating objects: 7, done.
685Counting objects: 100% (7/7), done.
686Delta compression using up to 8 threads
687Compressing objects: 100% (6/6), done.
688Writing objects: 100% (7/7), 662 bytes | 662.00 KiB/s, done.
689Total 7 (delta 0), reused 0 (delta 0), pack-reused 0 (from 0)
690To example.com:username/repo
691 * [new branch] main -> main
692branch 'main' set up to track 'origin/main'.
693-------------------------------------------
694
695Any time you want to set up a new repository, you can repeat steps
69612-14, with one exception: you only need to pass `--set-upstream` the first time
697you push. Afterwards you can just run the command:
698
699-------
700$ git push origin main
701-------
702
703Troubleshooting `git push`
704--------------------------
705
706There are 3 main errors you might run into when running `git push origin main`.
707Getting errors when running `git push` is actually a big part of using
708Git, so congratulations! If you get to this part of the tutorial, you
709get a little bonus experience in debugging.
710
711Here's a guide to why they're happening and how to fix them.
712
713**Problem 1: You pushed to `main`, but your branch actually isn't called `main`**
714
715Here's the error:
716
717-------
718$ git push origin main
719error: src refspec main does not match any
720-------
721
722This might happen if you didn't set `init.defaultBranch` to `main` in
723<<step_2,Step 2>>.
724
725If you want to check the name of your current branch, you can run `git
726status`. For example, in this output, the current branch is "master".
727
728-------------------------------------------
729$ git status
730On branch master
731
732...
733-------------------------------------------
734
735To push your branch, you have a few options:
736
737* rename your branch to `main`, by running `git branch -m main`
738 and then run `git push origin main`
739* run `git push origin master`
740 (where `master` is the name of your actual current branch)
741
742**Problem 2: SSH error**
743
744Here's the error:
745
746-----
747$ git push origin main
748The authenticity of host 'github.com (140.82.116.3)' can't be established.
749ED25519 key fingerprint is: SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU
750This key is not known by any other names.
751Are you sure you want to continue connecting (yes/no/[fingerprint])?
752-----
753
754Git uses SSH to connect during `git push`, and this message happens when
755SSH connects to a new site that you haven't connected to before.
756
757The easiest way to handle this is to type "yes" and press Enter.
758
759**Problem 3: the repository already has commits in it**
760
761Here's the error:
762
763---------------------
764$ git push origin main
765! [rejected] main -> main (fetch first)
766error: failed to push some refs to 'example.com:username/repo.git'
767hint: Updates were rejected because the remote contains work that you do not
768hint: have locally.
769---------------------
770
771If you see an error like this, it means that when you created the
772repository on your Git host, it added a commit to try to help you out.
773That's the "work that you do not have locally" in the error message.
774
775You should be able to fix this by redoing <<step_12,Step 12>>.
776Then <<step_14,Step 14>> should work.
777
778More useful Git commands
779------------------------
780
781We're not going to cover collaboration at all in this tutorial, but here are a
782few more commands that might be useful when using Git on your own:
783
784* To download a Git repository to use on your computer you can run
785 `git clone https://example.com/some/repo` (linkgit:git-clone[1]).
786* To tell Git to "un-add" a file that you added by accident, run
787 `git rm --cached FILENAME` (linkgit:git-rm[1])
788* To get a list of past commits, run `git log` (linkgit:git-log[1])
789* Every commit has an ID that looks something like this:
790 `497588f53141b531a59ed888c7d2d9b8f8a6742d`.
791 If you see a commit with `git log` that you want more details about,
792 you can run `git show COMMIT_ID` to see what changes that made since
793 the previous commit (linkgit:git-show[1])
794* To get a list of common Git commands, run `git help` (linkgit:git-help[1])
795
796GIT
797---
798Part of the linkgit:git[1] suite