@@ -495,8 +495,72 @@ moving backward and forward in time becomes much easier.
495
495
>
496
496
> `git checkout` can be used to restore a previous commit when unstaged changes have
497
497
> been made, but will it also work for changes that have been staged but not committed?
498
- > Make a change to `mars.txt`, add that change, and use `git checkout` to see if
499
- > you can remove your change.
498
+ > Make a change to `mars.txt`, add that change using `git add`,
499
+ > then use `git checkout` to see if you can remove your change.
500
+ > > ## Solution
501
+ > > After adding a change, `git checkout` can not be used directly.
502
+ > > Let's look at the output of `git status`:
503
+ > > ~~~
504
+ > > On branch main
505
+ > > Changes to be committed:
506
+ > > (use "git reset HEAD <file>..." to unstage)
507
+ > >
508
+ > > modified: mars.txt
509
+ > >
510
+ > > ~~~
511
+ > > {: .output}
512
+ > >
513
+ > > Note that if you don't have the same output
514
+ > > you may either have forgotten to change the file,
515
+ > > or you have added it *and* committed it.
516
+ > >
517
+ > > Using the command `git checkout -- mars.txt` now does not give an error,
518
+ > > but it does not restore the file either.
519
+ > > Git helpfully tells us that we need to use `git reset` first
520
+ > > to unstage the file:
521
+ > > ~~~
522
+ > > $ git reset HEAD mars.txt
523
+ > > ~~~
524
+ > > {: .language-bash}
525
+ > >
526
+ > > ~~~
527
+ > > Unstaged changes after reset:
528
+ > > M mars.txt
529
+ > > ~~~
530
+ > > {: .output}
531
+ > >
532
+ > > Now, `git status` gives us:
533
+ > > ~~~
534
+ > > $ git status
535
+ > > ~~~
536
+ > > {: .language-bash}
537
+ > >
538
+ > > ~~~
539
+ > > On branch main
540
+ > > Changes not staged for commit:
541
+ > > (use "git add <file>..." to update what will be committed)
542
+ > > (use "git checkout -- <file>..." to discard changes in working directory)
543
+ > >
544
+ > > modified: mars.txt
545
+ > >
546
+ > > no changes added to commit (use "git add" and/or "git commit -a")
547
+ > > ~~~
548
+ > > {: .output}
549
+ > >
550
+ > > This means we can now use `git checkout` to restore the file
551
+ > > to the previous commit:
552
+ > > ~~~
553
+ > > $ git checkout -- mars.txt
554
+ > > $ git status
555
+ > > ~~~
556
+ > > {: .language-bash}
557
+ > >
558
+ > > ~~~
559
+ > > On branch main
560
+ > > nothing to commit, working tree clean
561
+ > > ~~~
562
+ > > {: .output}
563
+ > {: .solution}
500
564
{: .challenge}
501
565
502
566
> ## Explore and Summarize Histories
0 commit comments