Git добавить в индекс несколько файлов
This command updates the index using the current content found in the working tree, to prepare the content staged for the next commit. It typically adds the current content of existing paths as a whole, but with some options it can also be used to add content with only part of the changes made to the working tree files applied, or remove paths that do not exist in the working tree anymore.
The "index" holds a snapshot of the content of the working tree, and it is this snapshot that is taken as the contents of the next commit. Thus after making any changes to the working tree, and before running the commit command, you must use the add command to add any new or modified files to the index.
This command can be performed multiple times before a commit. It only adds the content of the specified file(s) at the time the add command is run; if you want subsequent changes included in the next commit, then you must run git add again to add the new content to the index.
The git status command can be used to obtain a summary of which files have changes that are staged for the next commit.
The git add command will not add ignored files by default. If any ignored files were explicitly specified on the command line, git add will fail with a list of ignored files. Ignored files reached by directory recursion or filename globbing performed by Git (quote your globs before the shell) will be silently ignored. The git add command can be used to add ignored files with the -f (force) option.
Please see git-commit[1] for alternative ways to add content to a commit.
что происходит, когда вы добавляете (новый) файл в индекс
чтобы поставить что-то, вы обычно используете высокий уровень ("фарфор") . или точный эквивалент git stage (введено Скоттом Чаконом вокруг Git v1.6) который я нахожу гораздо более интуитивным, но не кажется таким популярным.
при добавлении новый файл в промежуточной области, три вещи происходят:
1 ответ 1
Давайте обозначим категории файлов, которые вообще можно добавлять. Будем использовать те же обозначения, что и в выводе команды git status -s :
M - (modified) отслеживаемые, изменились с прошлого коммита, еще не добавлены
D - (deleted) отслеживаемые, удалены после прошлого коммита, еще не добавлены
? - (untracked) неотслеживаемые, не запрещены к добавлению
! - (ignored) неотслеживаемые, запрещены к добавлению (например, в .gitignore )
Первое различие — в том, что . — это путь (аргумент), а всё остальное — параметры. Те и другие не исключают друг друга и возможны их сочетания.
Путь . обозначает текущую директорию, т.е. ту, в которой была запущена команда.
Начиная с Git версии 2.0, поведение команды add приведено в соответствие с поведением commit и других комманд. Теперь . обозначает не всю рабочую область (working tree), а текущий путь в этой области.
Таким образом, если вы выполняете команду add не в корневой директории проекта (той, где лежит .git/ ), то будет обработано содержимое только текущей директории.
Чтобы явным образом дать указание Git работать со всей рабочей областью, используйте :/ :
Если не указан никакой путь к добавляемым файлам, то большинство команд работает во всей рабочей области, а git add и git add --no-all просто не работают.
Git версии 2.0+ просматривает текущую папку и добавляет файлы M , D , ? .
Git версии 1.х просматривает всю рабочую область и добавляет файлы M , D .
Если '*' дается в кавычках, то обрабатывать его будет Git и это эквивалентно git add . . Исключение: из-под cmd.exe git add '*' не сработает, используйте git add . или git add * .
Эта команда в Git v. 2.0+ работает как git add . в Git v. 1.x, то есть добавляет измененные и новые файлы M , ? во всей рабочей области. Для этой команды обязательно указывать путь.
Git обновляет (update) статус уже отслеживаемых файлов т.е. M , D .
Эти варианты эквивалентны и добавляют M , D , ? .
Без точки — из всей рабочей области:
git add -A = git add -A :/ = git add :/ + git add -u
С точкой — только текущий путь:
git add -A . = git add . + git add -u .
Этот синтаксис лучше не использовать, и вот почему:
При этой команде shell (или bash или другая командная оболочка) просматривает рабочую область и отдает Git список файлов на добавление. Система сработает таким образом, что будут найдены абсолютно все не-скрытые файлы, находящиеся в заданном корне. Вы можете посмотреть на этот список, выполнив echo * . ( Исключение: из-под cmd.exe git add * работает так же как git add '*' на shell/bash. )
Произойдет следующее (здесь мы видим сразу несколько причин не использовать add * ):
Разнообразие параметров ( -u , -A , --no-all ) нужно для того, чтобы можно было добавлять разные группы файлов. Конкретно --no-all . было добавлено для того, чтобы реализовывать старое поведение add . в версиях 1.х.
Похоже, что несмотря на это, Git не позволяет добавлять конкретные группы файлов одной командой (см. сводную таблицу в начале).
Тонкости в использовании . и :/ нужны для того, чтобы каждую команду можно было выполнять как на всю рабочую область, так и на конкретную подпапку.
добавление файла в индекс с командами сантехники
прежде чем делать что-либо еще, идите вперед и вглядитесь в .
вы увидите, что она содержит только две (пустые) subdirecties: info и pack . Создайте файл, скажем README.md :
теперь давайте этапа README.md , шаг за шагом. Во-первых, используйте нижний уровень git hash-object команда на (1) хэш содержимое README.md и (2) Запишите последнее в репозиторий база данных.
( -w значит писать здесь.)
теперь, если вы посмотрите в .git/objects папка, вы увидите, что новый объект (blob) был добавлен в базу данных:
осталось одно, чтобы завершить постановку README.md . Нам нужно (3) зарегистрировать содержимое файла в индексе. Загляни внутрь .git , не должно быть файла с именем index в нем, пока. Теперь, если вы бежите
а потом еще один взгляд внутрь .git , вы увидите, что бинарные index файл создан.
вот и все. Вы инсценировали README.md . Он готов к следующему выступлению. Проверьте сами:
теперь вы можете сделать свой первый коммит, если хотите.
когда вы добавляете файл, он помечает его как файл, который вы зафиксируете после запуска команды git commit. Ярлык для автоматического добавления всех измененных файлов-это фиксация с помощью git commit-a. Другой ярлык, если вы добавляете несколько новых файлов одновременно, - запустить git add-A.
у меня есть куча файлов в наборе, но я хочу специально пропустить один измененный файл. Выглядит так после git status :
есть ли способ я могу сделать git add но просто игнорировать один текстовый файл, я не хочу трогать? Что-то вроде:
1) начать игнорировать изменения в одном уже версионном файле
и отменить, что git update-index --no-assume-unchanged "main/dontcheckmein.txt"
2) полностью игнорировать конкретный файл, препятствующий его созданию в репозитории
и .gitignore добавить относительный путь к файлу без ведущий ./
Итак, если ваш файл находится в MyProject/MyFolder/myfile.txt (где .git также на MyProject ), at .gitignore вы ставите только этот MyFolder/myfile.txt
вы можете подтвердить, какое правило связано с игнорированием с помощью git check-ignore "MyFolder/myfile.txt"
о глобальном игноре
эта ссылка говорит о ~/.gitignore_global ; но файл связан с вашим проектом; поэтому, если вы поместите шаблон exclude MyFolder/myfile.txt at ~/.gitignore_global , это будет работать, но не имеет особого смысла.
С другой стороны, если вы настроите ваш проект с git config core.excludesfile .gitignore здесь .gitignore на MyProject ; Эта настройка переопределит ~/.gitignore_global что может быть очень полезных правил.
Итак, на данный момент, я думаю, что лучше всего сделать какой-то скрипт, чтобы смешать ваш .gitignore С ~/.gitignore_global at .gitignore .
последнее предупреждение
Если файл, который вы хотите игнорировать, уже находится в репозитории, этот метод не будет работать, если вы этого не сделаете: git rm "MyFolder/myfile.txt" , но сначала создайте резервную копию, так как она будет удалена локально! вы можете скопировать его позже.
файл
В папке
хотя Бен Джексон прав,я подумал, что добавлю, как я использовал это решение. Ниже приведен очень простой скрипт, который я использую (который я называю gitadd), чтобы добавить все изменения, кроме нескольких, которые я храню в файле с именем .gittrackignore (очень похоже на то, как .gitignore works).
и это то, что мой нынешний .gittrackignore выглядит.
Я работаю на Android-проект, который я компилирую из командной строки при развертывании. Этот проект зависит на SherlockActionBar, поэтому на него нужно ссылаться в проекте.свойства, но это мешает компиляции, поэтому теперь я просто набираю gitadd и добавьте все изменения в git без необходимости отмены добавления проекта.свойства каждый раз.
теперь git поддерживает exclude certain paths and files по pathspec магии :(exclude) и его краткая форма :! . Таким образом, вы можете легко достичь этого, как следующая команда.
на самом деле вы можете указать больше:
git checkout -- main / dontcheckmein.txt
использовать git add -A добавить все измененные и новые файлы сразу.
Я использую git add --patch совсем немного и хотел что-то подобное, чтобы избежать попадания d все время через те же файлы. Я взбитые вверх очень hacky пару псевдонимов git, чтобы получить работу:
в моем случае я просто хотел игнорировать некоторые мини-файлы все время, но вы могли бы использовать переменную среды, такую как $GIT_EXCLUDE_PATTERN для более общего варианта использования.
для конкретного случая в вопросе самым простым способом было бы добавить все файлы с .c и оставить все остальное:
С git-scm (или/и man git add ):
git добавить
.
файлы для добавления содержимого. Fileglobs (например,*.c) можно дать для добавления всех соответствуя файлов.
обратите внимание, что это означает, что вы могли бы сделать что-то например:
добавить все файлы (которые не учитываются) в main папка. Вы даже можете пойти дикие с более сложными узорами:
выше будет добавить все файлы, находящиеся в и Service где-то в их именем.
очевидно, что вы не ограничены одним шаблоном для каждой команды. То есть вы можете попросить git добавить все файлы с расширением .c и .h:
этой ссылке может дать вам еще несколько идей шаблона глобуса.
Я нахожу это особенно полезным, когда я делаю много изменений, но все же хочу, чтобы мои обязательства оставались атомарными и отражали постепенный процесс, а не мешанину изменений, которые я могу работать в то время. Конечно, в какой-то момент стоимость разработки сложных шаблонов перевешивает стоимость добавления файлов более простыми методами или даже по одному файлу за раз. Однако большую часть времени я легко могу определить только файлы, которые мне нужны, с помощью простого шаблона и исключить все остальное.
кстати,мая нужно процитировать ваши шаблоны glob для их работы, но это никогда не было для меня.
Есть разные способы добавить все измененные файлы в индекс репозитория Git. В чем разница и зачем столько способов?
OPTIONS
Files to add content from. Fileglobs (e.g. *.c ) can be given to add all matching files. Also a leading directory name (e.g. dir to add dir/file1 and dir/file2 ) can be given to update the index to match the current state of the directory as a whole (e.g. specifying dir will record not just a file dir/file1 modified in the working tree, a file dir/file2 added to the working tree, but also a file dir/file3 removed from the working tree). Note that older versions of Git used to ignore removed files; use --no-all option if you want to add modified or new files but ignore removed ones.
For more details about the syntax, see the pathspec entry in gitglossary[7].
Don’t actually add the file(s), just show if they exist and/or will be ignored.
Allow adding otherwise ignored files.
Allow updating index entries outside of the sparse-checkout cone. Normally, git add refuses to update index entries whose paths do not fit within the sparse-checkout cone, since those files might be removed from the working tree without warning. See git-sparse-checkout[1] for more details.
Add modified contents in the working tree interactively to the index. Optional path arguments may be supplied to limit operation to a subset of the working tree. See “Interactive mode” for details.
Interactively choose hunks of patch between the index and the work tree and add them to the index. This gives the user a chance to review the difference before adding modified contents to the index.
This effectively runs add --interactive , but bypasses the initial command menu and directly jumps to the patch subcommand. See “Interactive mode” for details.
Open the diff vs. the index in an editor and let the user edit it. After the editor was closed, adjust the hunk headers and apply the patch to the index.
The intent of this option is to pick and choose lines of the patch to apply, or even to modify the contents of lines to be staged. This can be quicker and more flexible than using the interactive hunk selector. However, it is easy to confuse oneself and create a patch that does not apply to the index. See EDITING PATCHES below.
Update the index just where it already has an entry matching . This removes as well as modifies index entries to match the working tree, but adds no new files.
If no is given when -u option is used, all tracked files in the entire working tree are updated (old versions of Git used to limit the update to the current directory and its subdirectories).
Update the index not only where the working tree has a file matching but also where the index already has an entry. This adds, modifies, and removes index entries to match the working tree.
If no is given when -A option is used, all files in the entire working tree are updated (old versions of Git used to limit the update to the current directory and its subdirectories).
Update the index by adding new files that are unknown to the index and files modified in the working tree, but ignore files that have been removed from the working tree. This option is a no-op when no is used.
This option is primarily to help users who are used to older versions of Git, whose "git add …" was a synonym for "git add --no-all …", i.e. ignored removed files.
Record only the fact that the path will be added later. An entry for the path is placed in the index with no content. This is useful for, among other things, showing the unstaged content of such files with git diff and committing them with git commit -a .
Don’t add the file(s), but only refresh their stat() information in the index.
If some files could not be added because of errors indexing them, do not abort the operation, but continue adding the others. The command shall still exit with non-zero status. The configuration variable add.ignoreErrors can be set to true to make this the default behaviour.
This option can only be used together with --dry-run. By using this option the user can check if any of the given files would be ignored, no matter if they are already present in the work tree or not.
By default, git add will warn when adding an embedded repository to the index without using git submodule add to create an entry in .gitmodules . This option will suppress the warning (e.g., if you are manually performing operations on submodules).
Apply the "clean" process freshly to all tracked files to forcibly add them again to the index. This is useful after changing core.autocrlf configuration or the text attribute in order to correct files added with wrong CRLF/LF line endings. This option implies -u .
Override the executable bit of the added files. The executable bit is only changed in the index, the files on disk are left unchanged.
Pathspec is passed in instead of commandline args. If is exactly - then standard input is used. Pathspec elements are separated by LF or CR/LF. Pathspec elements can be quoted as explained for the configuration variable core.quotePath (see git-config[1]). See also --pathspec-file-nul and global --literal-pathspecs .
Only meaningful with --pathspec-from-file . Pathspec elements are separated with NUL character and all other characters are taken literally (including newlines and quotes).
This option can be used to separate command-line options from the list of files, (useful when filenames might be mistaken for command-line options).
INTERACTIVE MODE
When the command enters the interactive mode, it shows the output of the status subcommand, and then goes into its interactive command loop.
The command loop shows the list of subcommands available, and gives a prompt "What now> ". In general, when the prompt ends with a single >, you can pick only one of the choices given and type return, like this:
You also could say s or sta or status above as long as the choice is unique.
The main command loop has 6 subcommands (plus help and quit).
This shows the change between HEAD and index (i.e. what will be committed if you say git commit ), and between index and working tree files (i.e. what you could stage further before git commit using git add ) for each path. A sample output looks like this:
It shows that foo.jpg has differences from HEAD (but that is binary so line count cannot be shown) and there is no difference between indexed copy and the working tree version (if the working tree version were also different, binary would have been shown in place of nothing). The other file, git-add--interactive.perl, has 403 lines added and 35 lines deleted if you commit what is in the index, but working tree file has further modifications (one addition and one deletion).
This shows the status information and issues an "Update>>" prompt. When the prompt ends with double >>, you can make more than one selection, concatenated with whitespace or comma. Also you can say ranges. E.g. "2-5 7,9" to choose 2,3,4,5,7,9 from the list. If the second number in a range is omitted, all remaining patches are taken. E.g. "7-" to choose 7,8,9 from the list. You can say * to choose everything.
What you chose are then highlighted with *, like this:
To remove selection, prefix the input with - like this:
After making the selection, answer with an empty line to stage the contents of working tree files for selected paths in the index.
This has a very similar UI to update, and the staged information for selected paths are reverted to that of the HEAD version. Reverting new paths makes them untracked.
This has a very similar UI to update and revert, and lets you add untracked paths to the index.
This lets you choose one path out of a status like selection. After choosing the path, it presents the diff between the index and the working tree file and asks you if you want to stage the change of each hunk. You can select one of the following options and type return:
After deciding the fate for all hunks, if there is any hunk that was chosen, the index is updated with the selected hunks.
You can omit having to type return here, by setting the configuration variable interactive.singleKey to true .
This lets you review what will be committed (i.e. between HEAD and index).
полезная метафора
" добавление файла в индекс"," постановка файла"," добавление файла в промежуточную область " являются синонимами.
лично я предпочитаю термин постановка площадью to индекс потому что он поддается полезной метафорой. Если совершение сродни "фотографированию",постановка о "составление кадра".
представьте себя профессионалом фотограф собирается сделать фотографию класса А: вы собираете все свои предметы и готовите их к фотографии, вы убедитесь, что они все там и что нет злоумышленников, что все важное находится в кадре и т. д. Затем. Щелк!
конечно, если вы понимаете, сразу после съемки, что слишком много детей закрывали глаза (или что какой-то ребенок давал учителю кроличьи уши!), вы можете отказаться от этой первой фотографии и взять другой, лучший; в Git, это соответствовало бы изменение последнего коммита. Но я отвлекся.
EXAMPLES
Adds content from all *.txt files under Documentation directory and its subdirectories:
Note that the asterisk * is quoted from the shell in this example; this lets the command include the files from subdirectories of Documentation/ directory.
Considers adding content from all git-*.sh scripts:
Because this example lets the shell expand the asterisk (i.e. you are listing the files explicitly), it does not consider subdir/git-foo.sh .
EDITING PATCHES
Invoking git add -e or selecting e from the interactive hunk selector will open a patch in your editor; after the editor exits, the result is applied to the index. You are free to make arbitrary changes to the patch, but note that some changes may have confusing results, or even result in a patch that cannot be applied. If you want to abort the operation entirely (i.e., stage nothing new in the index), simply delete all lines of the patch. The list below describes some common things you may see in a patch, and which editing operations make sense on them.
Added content is represented by lines beginning with "+". You can prevent staging any addition lines by deleting them.
Removed content is represented by lines beginning with "-". You can prevent staging their removal by converting the "-" to a " " (space).
Modified content is represented by "-" lines (removing the old content) followed by "+" lines (adding the replacement content). You can prevent staging the modification by converting "-" lines to " ", and removing "+" lines. Beware that modifying only half of the pair is likely to introduce confusing changes to the index.
There are also more complex operations that can be performed. But beware that because the patch is applied only to the index and not the working tree, the working tree will appear to "undo" the change in the index. For example, introducing a new line into the index that is in neither the HEAD nor the working tree will stage the new line for commit, but the line will appear to be reverted in the working tree.
Avoid using these constructs, or do so with extreme caution.
Content which does not differ between the index and working tree may be shown on context lines, beginning with a " " (space). You can stage context lines for removal by converting the space to a "-". The resulting working tree file will appear to re-add the content.
modifying existing content
One can also modify context lines by staging them for removal (by converting " " to "-") and adding a "+" line with the new content. Similarly, one can modify "+" lines for existing additions or modifications. In all cases, the new modification will appear reverted in the working tree.
You may also add new content that does not exist in the patch; simply add new lines, each starting with "+". The addition will appear reverted in the working tree.
There are also several operations which should be avoided entirely, as they will make the patch impossible to apply:
это будет мое первое использование git. Я добавил новые файлы ( много ) в папку/проект ( локальный репозиторий git).
Я прошел через онлайн-уроки и форумы и вижу, что могу сделать
поэтому я иду в базовую папку репозитория и делаю
но затем появляются некоторые экраны и просят меня Добавить комментарий, который я делаю. я не знаю, что делать дальше и как выйти. Я не хочу испортить, поэтому я сделал ctrl + Z и не сделал что угодно.
не могли бы вы, ребята, изложить команды, которые мне нужно использовать?
чтобы добавить все внесенные вами изменения:
вы можете объединить эти шаги следующим образом:
git commit -a -m "MY MESSAGE HERE"
чтобы переместить внесенные изменения из локального репозитория в удаленный репозиторий:
git push origin master
возможно, вам придется ввести свое имя пользователя/пароль для github после этого. вот!--22--> хороший праймер по использованию git. Немного старомодно, но это хорошо покрывает то, что происходит.
использовать git add команда, за которой следует список имен файлов, разделенных пробелом, например
вы также можете выбрать несколько файлов, как это
добавить все файлы в указанной папке. Очень полезно, когда вы редактировать кучу файлов, но вы просто хотите зафиксировать некоторые из них.
как некоторые упоминали, возможный способ использует интерактивная постановка git. Это здорово, когда у вас есть файлы с разными расширениями
если вы нажмете 2 затем enter вы получите список доступных файлов, которые будут добавлены:
теперь вам просто нужно вставить количество файлов, которые вы хотите добавить, поэтому, если мы хотим добавить TODO и index.html мы типа 1,2
видишь * до номера? это означает, что файл был добавлен.
теперь представьте, что у вас есть 7 файлов и вы хотите добавить их все, кроме 7-го? Конечно, мы могли бы напечатать 1,2,3,4,5,6 но представьте, что вместо 7 у нас есть 16, что было бы довольно громоздко, хорошо, что нам не нужно вводить их все, потому что мы можем использовать диапазоны,набрав 1-6
мы даже можем использовать несколько диапазонов, поэтому, если мы хотим от 1 до 3 и от 5 до 7, мы вводим 1-3, 5-7 :
мы можно также использовать это для unstage файлов, если мы вводим -number , поэтому, если бы мы хотели unstage файл номер 1 мы бы ввести -1 :
и, как вы можете себе представить, мы также можем unstage ряд файлов, так что если мы наберем -range все файлы в этом диапазоне будут не загружены. Если бы мы хотели распаковать все файлы от 5 до 7, мы бы набрали -5-7 :
Если вы хотите добавить несколько файлов в определенной папке, вы можете разделить их с помощью . Это потрясающе для того, чтобы не повторять длинные пути, например
остерегайтесь не ставить пробелы между , .
когда вы меняете файлы или добавляете новые в репозиторий, вы сначала должны их этапировать.
или если вы хотите поставить все
делая это, вы говорите git, какие файлы вы хотите в своем следующем коммите. Вы тут:
где origin - это ветвь удаленного репозитория, а master-ваша локальная ветвь репозитория.
использовать git commit -a -m "my first commit message" , чтобы указать комментарий к коммиту в командной строке (с помощью этого не запустится редактор)
установить EDITOR переменная окружения для редактора, с которым вы знакомы
Если вы хотите, чтобы этап и зафиксировать все ваши файлы на Github сделать следующее;
git add -A
git commit -m "commit message"
git push origin master
в принципе, что означает действие, известное как" добавить в индекс " в Git? Я понимаю это так:
если для любого файла git вычисляет сумму SHA-1, то в основном добавление к индексу означает, что он вычисляет сумму SHA-1 и добавляет файл в промежуточную область.
Читайте также: