Разработка enterprise-продуктов: Cursor IDE, GitLab и шлюзы MCP
Данное произведение является техническим руководством. Все упомянутые конфигурации, IP-адреса и архитектурные схемы приведены исключительно в образовательных целях. Любые совпадения с реальными закрытыми инфраструктурами случайны.
Глава 1. Cursor IDE в закрытом контуре
Cursor IDE произвел революцию в написании кода благодаря глубокой интеграции с LLM (Claude 3.5, GPT-4). Однако для Enterprise-разработки возникает проблема безопасности: корпоративный код не должен утекать на публичные серверы OpenAI или Anthropic. Решением является использование Local-First моделей или защищенных корпоративных API (Azure OpenAI), а также локализация контекста. В книге описывается, как настроить Cursor так, чтобы он индексировал кодовую базу исключительно в зашифрованном виде и передавал телеметрию только через внутренние прокси-серверы компании.
Глава 2. Интеграция с On-Premise GitLab
Автоматизация написания кода бессмысленна без автоматизации его доставки. Мы рассмотрим построение моста между ИИ-агентами в Cursor и корпоративным сервером GitLab. С помощью протокола MCP (Model Context Protocol) и выделенного шлюза (runas-daemon) разработчик может прямо из редактора инициировать запуск GitLab CI/CD пайплайнов, читать логи упавших тестов и поручать ИИ их автоматическое исправление. Шлюз обеспечивает жесткую аутентификацию (через токены или Keycloak), не позволяя агенту выйти за пределы отведенных ему прав.
Приложение: Справочная документация GIT
GIT(1) Git Manual GIT(1)
NAME git – the stupid content tracker
SYNOPSIS git [-v | –version] [-h | –help] [-C <path>] [-c <name>=<value>] [–exec-path[=<path>]] [–html-path] [–man-path] [–info-path] [-p | –paginate | -P | –no-pager] [–no-replace-objects] [–no-lazy-fetch] [–no-optional-locks] [–no-advice] [–bare] [–git-dir=<path>] [–work-tree=<path>] [–namespace=<name>] [–config-env=<name>=<envvar>] <command> [<args>]
DESCRIPTION Git is a fast, scalable, distributed revision control system with an unusually rich command set that provides both high-level operations and full access to internals.
See gittutorial(7) to get started, then see giteveryday(7) for a useful minimum set of commands. The Git User’s Manual[1] has a more in-depth introduction.
After you mastered the basic concepts, you can come back to this page to learn what commands Git offers. You can learn more about individual Git commands with "git help command". gitcli(7) manual page gives you an overview of the command-line command syntax.
A formatted and hyperlinked copy of the latest Git documentation can be viewed at https://git.github.io/htmldocs/git.html or https://git-scm.com/docs.
OPTIONS -v, –version Prints the Git suite version that the git program came from.
This option is internally converted to git version … and accepts the same options as the git-version(1) command. If –help is also given, it takes precedence over –version.
–h, –help Prints the synopsis and a list of the most commonly used commands. If the option –all or -a is given then all available commands are printed. If a Git command is named this option will bring up the manual page for that command.
Other options are available to control how the manual page is displayed. See git-help(1) for more information, because git –help … is converted internally into git help ....
–C <path> Run as if git was started in <path> instead of the current working directory. When multiple -C options are given, each subsequent non-absolute -C <path> is interpreted relative to the preceding -C <path>. If <path> is present but empty, e.g. -C "", then the current working directory is left unchanged.
This option affects options that expect path name like –git-dir and –work-tree in that their interpretations of the path names would be made relative to the working directory caused by the -C option. For example the following invocations are equivalent:
git –git-dir=a.git –work-tree=b -C c status git –git-dir=c/a.git –work-tree=c/b status
–c <name>=<value> Pass a configuration parameter to the command. The value given will override values from configuration files. The <name> is expected in the same format as listed by git config (subkeys separated by dots).
Note that omitting the = in git -c foo.bar … is allowed and sets foo.bar to the boolean true value (just like [foo]bar would in a config file). Including the equals but with an empty value (like git -c foo.bar= …) sets foo.bar to the empty string which git config –type=bool will convert to false.
–-config-env=<name>=<envvar> Like -c <name>=<value>, give configuration variable <name> a value, where <envvar> is the name of an environment variable from which to retrieve the value. Unlike -c there is no shortcut for directly setting the value to an empty string, instead the environment variable itself must be set to the empty string. It is an error if the <envvar> does not exist in the environment. <envvar> may not contain an equals sign to avoid ambiguity with <name> containing one.
This is useful for cases where you want to pass transitory configuration options to git, but are doing so on operating systems where other processes might be able to read your command line (e.g. /proc/self/cmdline), but not your environment (e.g. /proc/self/environ). That behavior is the default on Linux, but may not be on your system.
Note that this might add security for variables such as http.extraHeader where the sensitive information is part of the value, but not e.g. url.<base>.insteadOf where the sensitive information can be part of the key.
–-exec-path[=<path>] Path to wherever your core Git programs are installed. This can also be controlled by setting the GIT_EXEC_PATH environment variable. If no path is given, git will print the current setting and then exit.
–-html-path Print the path, without trailing slash, where Git’s HTML documentation is installed and exit.
–-man-path Print the manpath (see man(1)) for the man pages for this version of Git and exit.
–-info-path Print the path where the Info files documenting this version of Git are installed and exit.
–p, –paginate Pipe all output into less (or if set, $PAGER) if standard output is a terminal. This overrides the pager.<cmd> configuration options (see the "Configuration Mechanism" section below).
–P, –no-pager Do not pipe Git output into a pager.
–-git-dir=<path> Set the path to the repository (".git" directory). This can also be controlled by setting the GIT_DIR environment variable. It can be an absolute path or relative path to current working directory.
Specifying the location of the ".git" directory using this option (or GIT_DIR environment variable) turns off the repository discovery that tries to find a directory with ".git" subdirectory (which is how the repository and the top-level of the working tree are discovered), and tells Git that you are at the top level of the working tree. If you are not at the top-level directory of the working tree, you should tell Git where the top-level of the working tree is, with the –work-tree=<path> option (or GIT_WORK_TREE environment variable)
If you just want to run git as if it was started in <path> then use git -C <path>.
–-work-tree=<path> Set the path to the working tree. It can be an absolute path or a path relative to the current working directory. This can also be controlled by setting the GIT_WORK_TREE environment variable and the core.worktree configuration variable (see core.worktree in git-config(1) for a more detailed discussion).
–-namespace=<path> Set the Git namespace. See gitnamespaces(7) for more details. Equivalent to setting the GIT_NAMESPACE environment variable.
–-bare Treat the repository as a bare repository. If GIT_DIR environment is not set, it is set to the current working directory.
–-no-replace-objects Do not use replacement refs to replace Git objects. This is equivalent to exporting the GIT_NO_REPLACE_OBJECTS environment variable with any value. See git-replace(1) for more information.
–-no-lazy-fetch Do not fetch missing objects from the promisor remote on demand. Useful together with git cat-file -e <object> to see if the object is locally available. This is equivalent to setting the GIT_NO_LAZY_FETCH environment variable to 1.
–-no-optional-locks Do not perform optional operations that require locks. This is equivalent to setting the GIT_OPTIONAL_LOCKS to 0.
–-no-advice Disable all advice hints from being printed.
–-literal-pathspecs Treat pathspecs literally (i.e. no globbing, no pathspec magic). This is equivalent to setting the GIT_LITERAL_PATHSPECS environment variable to 1.
–-glob-pathspecs Add "glob" magic to all pathspec. This is equivalent to setting the GIT_GLOB_PATHSPECS environment variable to 1. Disabling globbing on individual pathspecs can be done using pathspec magic ":(literal)"
–-noglob-pathspecs Add "literal" magic to all pathspec. This is equivalent to setting the GIT_NOGLOB_PATHSPECS environment variable to 1. Enabling globbing on individual pathspecs can be done using pathspec magic ":(glob)"
–-icase-pathspecs Add "icase" magic to all pathspec. This is equivalent to setting the GIT_ICASE_PATHSPECS environment variable to 1.
–-list-cmds=<group>[,<group>…] List commands by group. This is an internal/experimental option and may change or be removed in the future. Supported groups are: builtins, parseopt (builtin commands that use parse-options), main (all commands in libexec directory), others (all other commands in $PATH that have git- prefix), list-<category> (see categories in command-list.txt), nohelpers (exclude helper commands), alias and config (retrieve command list from config variable completion.commands)
–-attr-source=<tree-ish> Read gitattributes from <tree-ish> instead of the worktree. See gitattributes(5). This is equivalent to setting the GIT_ATTR_SOURCE environment variable.
GIT COMMANDS We divide Git into high level ("porcelain") commands and low level ("plumbing") commands.
HIGH-LEVEL COMMANDS (PORCELAIN) We separate the porcelain commands into the main commands and some ancillary user utilities.
Main porcelain commands git-add(1) Add file contents to the index.
git-am(1) Apply a series of patches from a mailbox.
git-archive(1) Create an archive of files from a named tree.
git-bisect(1) Use binary search to find the commit that introduced a bug.
git-branch(1) List, create, or delete branches.
git-bundle(1) Move objects and refs by archive.
git-checkout(1) Switch branches or restore working tree files.
git-cherry-pick(1) Apply the changes introduced by some existing commits.
git-citool(1) Graphical alternative to git-commit.
git-clean(1) Remove untracked files from the working tree.
git-clone(1) Clone a repository into a new directory.
git-commit(1) Record changes to the repository.
git-describe(1) Give an object a human readable name based on an available ref.
git-diff(1) Show changes between commits, commit and working tree, etc.
git-fetch(1) Download objects and refs from another repository.
git-format-patch(1) Prepare patches for e-mail submission.
git-gc(1) Cleanup unnecessary files and optimize the local repository.
git-grep(1) Print lines matching a pattern.
git-gui(1) A portable graphical interface to Git.
git-init(1) Create an empty Git repository or reinitialize an existing one.
git-log(1) Show commit logs.
git-maintenance(1) Run tasks to optimize Git repository data.
git-merge(1) Join two or more development histories together.
git-mv(1) Move or rename a file, a directory, or a symlink.
git-notes(1) Add or inspect object notes.
git-pull(1) Fetch from and integrate with another repository or a local branch.
git-push(1) Update remote refs along with associated objects.
git-range-diff(1) Compare two commit ranges (e.g. two versions of a branch).
git-rebase(1) Reapply commits on top of another base tip.
git-reset(1) Reset current HEAD to the specified state.
git-restore(1) Restore working tree files.
git-revert(1) Revert some existing commits.
git-rm(1) Remove files from the working tree and from the index.
git-shortlog(1) Summarize git log output.
git-show(1) Show various types of objects.
git-sparse-checkout(1) Reduce your working tree to a subset of tracked files.
git-stash(1) Stash the changes in a dirty working directory away.
git-status(1) Show the working tree status.
git-submodule(1) Initialize, update or inspect submodules.
git-switch(1) Switch branches.
git-tag(1) Create, list, delete or verify a tag object signed with GPG.
git-worktree(1) Manage multiple working trees.
gitk(1) The Git repository browser.
scalar(1) A tool for managing large Git repositories.
Ancillary Commands Manipulators:
git-config(1) Get and set repository or global options.
git-fast-export(1) Git data exporter.
git-fast-import(1) Backend for fast Git data importers.
git-filter-branch(1) Rewrite branches.
git-mergetool(1) Run merge conflict resolution tools to resolve merge conflicts.
git-pack-refs(1) Pack heads and tags for efficient repository access.
git-prune(1) Prune all unreachable objects from the object database.
git-reflog(1) Manage reflog information.
git-refs(1) Low-level access to refs.
git-remote(1) Manage set of tracked repositories.
git-repack(1) Pack unpacked objects in a repository.
git-replace(1) Create, list, delete refs to replace objects.
Interrogators:
git-annotate(1) Annotate file lines with commit information.
git-blame(1) Show what revision and author last modified each line of a file.
git-bugreport(1) Collect information for user to file a bug report.
git-count-objects(1) Count unpacked number of objects and their disk consumption.
git-diagnose(1) Generate a zip archive of diagnostic information.
git-difftool(1) Show changes using common diff tools.
git-fsck(1) Verifies the connectivity and validity of the objects in the database.
git-help(1) Display help information about Git.
git-instaweb(1) Instantly browse your working repository in gitweb.
git-merge-tree(1) Perform merge without touching index or working tree.
git-rerere(1) Reuse recorded resolution of conflicted merges.
git-show-branch(1) Show branches and their commits.
git-verify-commit(1) Check the GPG signature of commits.
git-verify-tag(1) Check the GPG signature of tags.
git-version(1) Display version information about Git.
git-whatchanged(1) Show logs with differences each commit introduces.
gitweb(1) Git web interface (web frontend to Git repositories).
Interacting with Others These commands are to interact with foreign SCM and with other people via patch over e-mail.
git-imap-send(1) Send a collection of patches from stdin to an IMAP folder.
git-quiltimport(1) Applies a quilt patchset onto the current branch.
git-request-pull(1) Generates a summary of pending changes.
git-send-email(1) Send a collection of patches as emails.
git-svn(1) Bidirectional operation between a Subversion repository and Git.
Reset, restore and revert There are three commands with similar names: git reset, git restore and git revert.
• git-revert(1) is about making a new commit that reverts the changes made by other commits.
• git-restore(1) is about restoring files in the working tree from either the index or another commit. This command does not update your branch. The command can also be used to restore files in the index from another commit.
• git-reset(1) is about updating your branch, moving the tip in order to add or remove commits from the branch. This operation changes the commit history.
git reset can also be used to restore the index, overlapping with git restore.
LOW-LEVEL COMMANDS (PLUMBING) Although Git includes its own porcelain layer, its low-level commands are sufficient to support development of alternative porcelains. Developers of such porcelains might start by reading about git-update-index(1) and git-read-tree(1).
The interface (input, output, set of options and the semantics) to these low-level commands are meant to be a lot more stable than Porcelain level commands, because these commands are primarily for scripted use. The interface to Porcelain commands on the other hand are subject to change in order to improve the end user experience.
The following description divides the low-level commands into commands that manipulate objects (in the repository, index, and working tree), commands that interrogate and compare objects, and commands that move objects and references between repositories.
Manipulation commands git-apply(1) Apply a patch to files and/or to the index.
git-checkout-index(1) Copy files from the index to the working tree.
git-commit-graph(1) Write and verify Git commit-graph files.
git-commit-tree(1) Create a new commit object.
git-hash-object(1) Compute object ID and optionally create an object from a file.
git-index-pack(1) Build pack index file for an existing packed archive.
git-merge-file(1) Run a three-way file merge.
git-merge-index(1) Run a merge for files needing merging.
git-mktag(1) Creates a tag object with extra validation.
git-mktree(1) Build a tree-object from ls-tree formatted text.
git-multi-pack-index(1) Write and verify multi-pack-indexes.
git-pack-objects(1) Create a packed archive of objects.
git-prune-packed(1) Remove extra objects that are already in pack files.
git-read-tree(1) Reads tree information into the index.
git-replay(1) EXPERIMENTAL: Replay commits on a new base, works with bare repos too.
git-symbolic-ref(1) Read, modify and delete symbolic refs.
git-unpack-objects(1) Unpack objects from a packed archive.
git-update-index(1) Register file contents in the working tree to the index.
git-update-ref(1) Update the object name stored in a ref safely.
git-write-tree(1) Create a tree object from the current index.
Interrogation commands git-cat-file(1) Provide contents or details of repository objects.
git-cherry(1) Find commits yet to be applied to upstream.
git-diff-files(1) Compares files in the working tree and the index.
git-diff-index(1) Compare a tree to the working tree or index.
git-diff-tree(1) Compares the content and mode of blobs found via two tree objects.
git-for-each-ref(1) Output information on each ref.
git-for-each-repo(1) Run a Git command on a list of repositories.
git-get-tar-commit-id(1) Extract commit ID from an archive created using git-archive.
git-ls-files(1) Show information about files in the index and the working tree.
git-ls-remote(1) List references in a remote repository.
git-ls-tree(1) List the contents of a tree object.
git-merge-base(1) Find as good common ancestors as possible for a merge.
git-name-rev(1) Find symbolic names for given revs.
git-pack-redundant(1) Find redundant pack files.
git-rev-list(1) Lists commit objects in reverse chronological order.
git-rev-parse(1) Pick out and massage parameters.
git-show-index(1) Show packed archive index.
git-show-ref(1) List references in a local repository.
git-unpack-file(1) Creates a temporary file with a blob’s contents.
git-var(1) Show a Git logical variable.
git-verify-pack(1) Validate packed Git archive files.
In general, the interrogate commands do not touch the files in the working tree.
Syncing repositories git-daemon(1) A really simple server for Git repositories.
git-fetch-pack(1) Receive missing objects from another repository.
git-http-backend(1) Server side implementation of Git over HTTP.
git-send-pack(1) Push objects over Git protocol to another repository.
git-update-server-info(1) Update auxiliary info file to help dumb servers.
The following are helper commands used by the above; end users typically do not use them directly.
git-http-fetch(1) Download from a remote Git repository via HTTP.
git-http-push(1) Push objects over HTTP/DAV to another repository.
git-receive-pack(1) Receive what is pushed into the repository.
git-shell(1) Restricted login shell for Git-only SSH access.
git-upload-archive(1) Send archive back to git-archive.
git-upload-pack(1) Send objects packed back to git-fetch-pack.
Internal helper commands These are internal helper commands used by other commands; end users typically do not use them directly.
git-check-attr(1) Display gitattributes information.
git-check-ignore(1) Debug gitignore / exclude files.
git-check-mailmap(1) Show canonical names and email addresses of contacts.
git-check-ref-format(1) Ensures that a reference name is well formed.
git-column(1) Display data in columns.
git-credential(1) Retrieve and store user credentials.
git-credential-cache(1) Helper to temporarily store passwords in memory.
git-credential-store(1) Helper to store credentials on disk.
git-fmt-merge-msg(1) Produce a merge commit message.
git-hook(1) Run git hooks.
git-interpret-trailers(1) Add or parse structured information in commit messages.
git-mailinfo(1) Extracts patch and authorship from a single e-mail message.
git-mailsplit(1) Simple UNIX mbox splitter program.
git-merge-one-file(1) The standard helper program to use with git-merge-index.
git-patch-id(1) Compute unique ID for a patch.
git-sh-i18n(1) Git’s i18n setup code for shell scripts.
git-sh-setup(1) Common Git shell script setup code.
git-stripspace(1) Remove unnecessary whitespace.
GUIDES The following documentation pages are guides about Git concepts.
gitcore-tutorial(7) A Git core tutorial for developers.
gitcredentials(7) Providing usernames and passwords to Git.
gitcvs-migration(7) Git for CVS users.
gitdiffcore(7) Tweaking diff output.
giteveryday(7) A useful minimum set of commands for Everyday Git.
gitfaq(7) Frequently asked questions about using Git.
gitglossary(7) A Git Glossary.
gitnamespaces(7) Git namespaces.
gitremote-helpers(7) Helper programs to interact with remote repositories.
gitsubmodules(7) Mounting one repository inside another.
gittutorial(7) A tutorial introduction to Git.
gittutorial-2(7) A tutorial introduction to Git: part two.
gitworkflows(7) An overview of recommended workflows with Git.
REPOSITORY, COMMAND AND FILE INTERFACES This documentation discusses repository and command interfaces which users are expected to interact with directly. See –user-formats in git-help(1) for more details on the criteria.
gitattributes(5) Defining attributes per path.
gitcli(7) Git command-line interface and conventions.
githooks(5) Hooks used by Git.
gitignore(5) Specifies intentionally untracked files to ignore.
gitmailmap(5) Map author/committer names and/or E-Mail addresses.
gitmodules(5) Defining submodule properties.
gitrepository-layout(5) Git Repository Layout.
gitrevisions(7) Specifying revisions and ranges for Git.
FILE FORMATS, PROTOCOLS AND OTHER DEVELOPER INTERFACES This documentation discusses file formats, over-the-wire protocols and other git developer interfaces. See –developer-interfaces in git-help(1).
gitformat-bundle(5) The bundle file format.
gitformat-chunk(5) Chunk-based file formats.
gitformat-commit-graph(5) Git commit-graph format.
gitformat-index(5) Git index format.
gitformat-pack(5) Git pack format.
gitformat-signature(5) Git cryptographic signature formats.
gitprotocol-capabilities(5) Protocol v0 and v1 capabilities.
gitprotocol-common(5) Things common to various protocols.
gitprotocol-http(5) Git HTTP-based protocols.
gitprotocol-pack(5) How packs are transferred over-the-wire.
gitprotocol-v2(5) Git Wire Protocol, Version 2.
CONFIGURATION MECHANISM Git uses a simple text format to store customizations that are per repository and are per user. Such a configuration file may look like this:
# # A '#' or ';' character indicates a comment. #
; core variables [core] ; Don't trust file modes filemode = false
; user identity [user] name = "Junio C Hamano" email = "gitster@pobox.com"
Various commands read from the configuration file and adjust their operation accordingly. See git-config(1) for a list and more details about the configuration mechanism.
IDENTIFIER TERMINOLOGY <object> Indicates the object name for any type of object.
<blob> Indicates a blob object name.
<tree> Indicates a tree object name.
<commit> Indicates a commit object name.
<tree-ish> Indicates a tree, commit or tag object name. A command that takes a <tree-ish> argument ultimately wants to operate on a <tree> object but automatically dereferences <commit> and <tag> objects that point at a <tree>.
<commit-ish> Indicates a commit or tag object name. A command that takes a <commit-ish> argument ultimately wants to operate on a <commit> object but automatically dereferences <tag> objects that point at a <commit>.
<type> Indicates that an object type is required. Currently one of: blob, tree, commit, or tag.
<file> Indicates a filename – almost always relative to the root of the tree structure GIT_INDEX_FILE describes.
SYMBOLIC IDENTIFIERS Any Git command accepting any <object> can also use the following symbolic notation:
HEAD indicates the head of the current branch.
<tag> a valid tag name (i.e. a refs/tags/<tag> reference).
<head> a valid head name (i.e. a refs/heads/<head> reference).
For a more complete list of ways to spell object names, see "SPECIFYING REVISIONS" section in gitrevisions(7).
FILE/DIRECTORY STRUCTURE Please see the gitrepository-layout(5) document.
Read githooks(5) for more details about each hook.
Higher level SCMs may provide and manage additional information in the $GIT_DIR.
TERMINOLOGY Please see gitglossary(7).
ENVIRONMENT VARIABLES Various Git commands pay attention to environment variables and change their behavior. The environment variables marked as "Boolean" take their values the same way as Boolean valued configuration variables, e.g. "true", "yes", "on" and positive numbers are taken as "yes".
Here are the variables:
The Git Repository These environment variables apply to all core Git commands. Nb: it is worth noting that they may be used/overridden by SCMS sitting above Git so take care if using a foreign front-end.
GIT_INDEX_FILE This environment variable specifies an alternate index file. If not specified, the default of $GIT_DIR/index is used.
GIT_INDEX_VERSION This environment variable specifies what index version is used when writing the index file out. It won’t affect existing index files. By default index file version 2 or 3 is used. See git-update-index(1) for more information.
GIT_OBJECT_DIRECTORY If the object storage directory is specified via this environment variable then the sha1 directories are created underneath – otherwise the default $GIT_DIR/objects directory is used.
GIT_ALTERNATE_OBJECT_DIRECTORIES Due to the immutable nature of Git objects, old objects can be archived into shared, read-only directories. This variable specifies a ":" separated (on Windows ";" separated) list of Git object directories which can be used to search for Git objects. New objects will not be written to these directories.
Entries that begin with " (double-quote) will be interpreted as C-style quoted paths, removing leading and trailing double-quotes and respecting backslash escapes. E.g., the value "path-with-\"-and-:-in-it":vanilla-path has two paths: path-with-"-and-:-in-it and vanilla-path.
GIT_DIR If the GIT_DIR environment variable is set then it specifies a path to use instead of the default .git for the base of the repository. The –git-dir command-line option also sets this value.
GIT_WORK_TREE Set the path to the root of the working tree. This can also be controlled by the –work-tree command-line option and the core.worktree configuration variable.
GIT_NAMESPACE Set the Git namespace; see gitnamespaces(7) for details. The –namespace command-line option also sets this value.
GIT_CEILING_DIRECTORIES This should be a colon-separated list of absolute paths. If set, it is a list of directories that Git should not chdir up into while looking for a repository directory (useful for excluding slow-loading network directories). It will not exclude the current working directory or a GIT_DIR set on the command line or in the environment. Normally, Git has to read the entries in this list and resolve any symlink that might be present in order to compare them with the current directory. However, if even this access is slow, you can add an empty entry to the list to tell Git that the subsequent entries are not symlinks and needn’t be resolved; e.g., GIT_CEILING_DIRECTORIES=/maybe/symlink::/very/slow/non/symlink.
GIT_DISCOVERY_ACROSS_FILESYSTEM When run in a directory that does not have ".git" repository directory, Git tries to find such a directory in the parent directories to find the top of the working tree, but by default it does not cross filesystem boundaries. This Boolean environment variable can be set to true to tell Git not to stop at filesystem boundaries. Like GIT_CEILING_DIRECTORIES, this will not affect an explicit repository directory set via GIT_DIR or on the command line.
GIT_COMMON_DIR If this variable is set to a path, non-worktree files that are normally in $GIT_DIR will be taken from this path instead. Worktree-specific files such as HEAD or index are taken from $GIT_DIR. See gitrepository-layout(5) and git-worktree(1) for details. This variable has lower precedence than other path variables such as GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY…
GIT_DEFAULT_HASH If this variable is set, the default hash algorithm for new repositories will be set to this value. This value is ignored when cloning and the setting of the remote repository is always used. The default is "sha1". See –object-format in git-init(1).
GIT_DEFAULT_REF_FORMAT If this variable is set, the default reference backend format for new repositories will be set to this value. The default is "files". See –ref-format in git-init(1).
Git Commits GIT_AUTHOR_NAME The human-readable name used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides the user.name and author.name configuration settings.
GIT_AUTHOR_EMAIL The email address used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides the user.email and author.email configuration settings.
GIT_AUTHOR_DATE The date used for the author identity when creating commit or tag objects, or when writing reflogs. See git-commit(1) for valid formats.
GIT_COMMITTER_NAME The human-readable name used in the committer identity when creating commit or tag objects, or when writing reflogs. Overrides the user.name and committer.name configuration settings.
GIT_COMMITTER_EMAIL The email address used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides the user.email and committer.email configuration settings.
GIT_COMMITTER_DATE The date used for the committer identity when creating commit or tag objects, or when writing reflogs. See git-commit(1) for valid formats.
EMAIL The email address used in the author and committer identities if no other relevant environment variable or configuration setting has been set.
Git Diffs GIT_DIFF_OPTS Only valid setting is "–unified=??" or "-u??" to set the number of context lines shown when a unified diff is created. This takes precedence over any "-U" or "–unified" option value passed on the Git diff command line.
GIT_EXTERNAL_DIFF When the environment variable GIT_EXTERNAL_DIFF is set, the program named by it is called to generate diffs, and Git does not use its builtin diff machinery. For a path that is added, removed, or modified, GIT_EXTERNAL_DIFF is called with 7 parameters:
path old-file old-hex old-mode new-file new-hex new-mode
where:
<old|new>-file are files GIT_EXTERNAL_DIFF can use to read the contents of <old|new>,
<old|new>-hex are the 40-hexdigit SHA-1 hashes,
<old|new>-mode are the octal representation of the file modes.
The file parameters can point at the user’s working file (e.g. new-file in "git-diff-files"), /dev/null (e.g. old-file when a new file is added), or a temporary file (e.g. old-file in the index). GIT_EXTERNAL_DIFF should not worry about unlinking the temporary file – it is removed when GIT_EXTERNAL_DIFF exits.
For a path that is unmerged, GIT_EXTERNAL_DIFF is called with 1 parameter, <path>.
For each path GIT_EXTERNAL_DIFF is called, two environment variables, GIT_DIFF_PATH_COUNTER and GIT_DIFF_PATH_TOTAL are set.
GIT_EXTERNAL_DIFF_TRUST_EXIT_CODE If this Boolean environment variable is set to true then the GIT_EXTERNAL_DIFF command is expected to return exit code 0 if it considers the input files to be equal or 1 if it considers them to be different, like diff(1). If it is set to false, which is the default, then the command is expected to return exit code 0 regardless of equality. Any other exit code causes Git to report a fatal error.
GIT_DIFF_PATH_COUNTER A 1-based counter incremented by one for every path.
GIT_DIFF_PATH_TOTAL The total number of paths.
other GIT_MERGE_VERBOSITY A number controlling the amount of output shown by the recursive merge strategy. Overrides merge.verbosity. See git-merge(1)
GIT_PAGER This environment variable overrides $PAGER. If it is set to an empty string or to the value "cat", Git will not launch a pager. See also the core.pager option in git-config(1).
GIT_PROGRESS_DELAY A number controlling how many seconds to delay before showing optional progress indicators. Defaults to 2.
GIT_EDITOR This environment variable overrides $EDITOR and $VISUAL. It is used by several Git commands when, on interactive mode, an editor is to be launched. See also git-var(1) and the core.editor option in git-config(1).
GIT_SEQUENCE_EDITOR This environment variable overrides the configured Git editor when editing the todo list of an interactive rebase. See also git-rebase(1) and the sequence.editor option in git-config(1).
GIT_SSH, GIT_SSH_COMMAND If either of these environment variables is set then git fetch and git push will use the specified command instead of ssh when they need to connect to a remote system. The command-line parameters passed to the configured command are determined by the ssh variant. See ssh.variant option in git-config(1) for details.
$GIT_SSH_COMMAND takes precedence over $GIT_SSH, and is interpreted by the shell, which allows additional arguments to be included. $GIT_SSH on the other hand must be just the path to a program (which can be a wrapper shell script, if additional arguments are needed).
Usually it is easier to configure any desired options through your personal .ssh/config file. Please consult your ssh documentation for further details.
GIT_SSH_VARIANT If this environment variable is set, it overrides Git’s autodetection whether GIT_SSH/GIT_SSH_COMMAND/core.sshCommand refer to OpenSSH, plink or tortoiseplink. This variable overrides the config setting ssh.variant that serves the same purpose.
GIT_SSL_NO_VERIFY Setting and exporting this environment variable to any value tells Git not to verify the SSL certificate when fetching or pushing over HTTPS.
GIT_ATTR_SOURCE Sets the treeish that gitattributes will be read from.
GIT_ASKPASS If this environment variable is set, then Git commands which need to acquire passwords or passphrases (e.g. for HTTP or IMAP authentication) will call this program with a suitable prompt as command-line argument and read the password from its STDOUT. See also the core.askPass option in git- config(1).
GIT_TERMINAL_PROMPT If this Boolean environment variable is set to false, git will not prompt on the terminal (e.g., when asking for HTTP authentication).
GIT_CONFIG_GLOBAL, GIT_CONFIG_SYSTEM Take the configuration from the given files instead from global or system-level configuration files. If GIT_CONFIG_SYSTEM is set, the system config file defined at build time (usually /etc/gitconfig) will not be read. Likewise, if GIT_CONFIG_GLOBAL is set, neither $HOME/.gitconfig nor $XDG_CONFIG_HOME/git/config will be read. Can be set to /dev/null to skip reading configuration files of the respective level.
GIT_CONFIG_NOSYSTEM Whether to skip reading settings from the system-wide $(prefix)/etc/gitconfig file. This Boolean environment variable can be used along with $HOME and $XDG_CONFIG_HOME to create a predictable environment for a picky script, or you can set it to true to temporarily avoid using a buggy /etc/gitconfig file while waiting for someone with sufficient permissions to fix it.
GIT_FLUSH If this Boolean environment variable is set to true, then commands such as git blame (in incremental mode), git rev-list, git log, git check-attr and git check-ignore will force a flush of the output stream after each record have been flushed. If this variable is set to false, the output of these commands will be done using completely buffered I/O. If this environment variable is not set, Git will choose buffered or record-oriented flushing based on whether stdout appears to be redirected to a file or not.
GIT_TRACE Enables general trace messages, e.g. alias expansion, built-in command execution and external command execution.
If this variable is set to "1", "2" or "true" (comparison is case insensitive), trace messages will be printed to stderr.
If the variable is set to an integer value greater than 2 and lower than 10 (strictly) then Git will interpret this value as an open file descriptor and will try to write the trace messages into this file descriptor.
Alternatively, if the variable is set to an absolute path (starting with a / character), Git will interpret this as a file path and will try to append the trace messages to it.
Unsetting the variable, or setting it to empty, "0" or "false" (case insensitive) disables trace messages.
GIT_TRACE_FSMONITOR Enables trace messages for the filesystem monitor extension. See GIT_TRACE for available trace output options.
GIT_TRACE_PACK_ACCESS Enables trace messages for all accesses to any packs. For each access, the pack file name and an offset in the pack is recorded. This may be helpful for troubleshooting some pack-related performance problems. See GIT_TRACE for available trace output options.
GIT_TRACE_PACKET Enables trace messages for all packets coming in or out of a given program. This can help with debugging object negotiation or other protocol issues. Tracing is turned off at a packet starting with "PACK" (but see GIT_TRACE_PACKFILE below). See GIT_TRACE for available trace output options.
GIT_TRACE_PACKFILE Enables tracing of packfiles sent or received by a given program. Unlike other trace output, this trace is verbatim: no headers, and no quoting of binary data. You almost certainly want to direct into a file (e.g., GIT_TRACE_PACKFILE=/tmp/my.pack) rather than displaying it on the terminal or mixing it with other trace output.
Note that this is currently only implemented for the client side of clones and fetches.
GIT_TRACE_PERFORMANCE Enables performance related trace messages, e.g. total execution time of each Git command. See GIT_TRACE for available trace output options.
GIT_TRACE_REFS Enables trace messages for operations on the ref database. See GIT_TRACE for available trace output options.
GIT_TRACE_SETUP Enables trace messages printing the .git, working tree and current working directory after Git has completed its setup phase. See GIT_TRACE for available trace output options.
GIT_TRACE_SHALLOW Enables trace messages that can help debugging fetching / cloning of shallow repositories. See GIT_TRACE for available trace output options.
GIT_TRACE_CURL Enables a curl full trace dump of all incoming and outgoing data, including descriptive information, of the git transport protocol. This is similar to doing curl –trace-ascii on the command line. See GIT_TRACE for available trace output options.
GIT_TRACE_CURL_NO_DATA When a curl trace is enabled (see GIT_TRACE_CURL above), do not dump data (that is, only dump info lines and headers).
GIT_TRACE2 Enables more detailed trace messages from the "trace2" library. Output from GIT_TRACE2 is a simple text-based format for human readability.
If this variable is set to "1", "2" or "true" (comparison is case insensitive), trace messages will be printed to stderr.
If the variable is set to an integer value greater than 2 and lower than 10 (strictly) then Git will interpret this value as an open file descriptor and will try to write the trace messages into this file descriptor.
Alternatively, if the variable is set to an absolute path (starting with a / character), Git will interpret this as a file path and will try to append the trace messages to it. If the path already exists and is a directory, the trace messages will be written to files (one per process) in that directory, named according to the last component of the SID and an optional counter (to avoid filename collisions).
In addition, if the variable is set to af_unix:[<socket-type>:]<absolute-pathname>, Git will try to open the path as a Unix Domain Socket. The socket type can be either stream or dgram.
Unsetting the variable, or setting it to empty, "0" or "false" (case insensitive) disables trace messages.
See Trace2 documentation[2] for full details.
GIT_TRACE2_EVENT This setting writes a JSON-based format that is suited for machine interpretation. See GIT_TRACE2 for available trace output options and Trace2 documentation[2] for full details.
GIT_TRACE2_PERF In addition to the text-based messages available in GIT_TRACE2, this setting writes a column-based format for understanding nesting regions. See GIT_TRACE2 for available trace output options and Trace2 documentation[2] for full details.
GIT_TRACE_REDACT By default, when tracing is activated, Git redacts the values of cookies, the "Authorization:" header, the "Proxy-Authorization:" header and packfile URIs. Set this Boolean environment variable to false to prevent this redaction.
GIT_NO_REPLACE_OBJECTS Setting and exporting this environment variable tells Git to ignore replacement refs and do not replace Git objects.
GIT_LITERAL_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs literally, rather than as glob patterns. For example, running GIT_LITERAL_PATHSPECS=1 git log – '*.c' will search for commits that touch the path *.c, not any paths that the glob *.c matches. You might want this if you are feeding literal paths to Git (e.g., paths previously given to you by git ls-tree, –raw diff output, etc).
GIT_GLOB_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs as glob patterns (aka "glob" magic).
GIT_NOGLOB_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs as literal (aka "literal" magic).
GIT_ICASE_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs as case-insensitive.
GIT_NO_LAZY_FETCH Setting this Boolean environment variable to true tells Git not to lazily fetch missing objects from the promisor remote on demand.
GIT_REFLOG_ACTION When a ref is updated, reflog entries are created to keep track of the reason why the ref was updated (which is typically the name of the high-level command that updated the ref), in addition to the old and new values of the ref. A scripted Porcelain command can use set_reflog_action helper function in git-sh-setup to set its name to this variable when it is invoked as the top level command by the end user, to be recorded in the body of the reflog.
GIT_REF_PARANOIA If this Boolean environment variable is set to false, ignore broken or badly named refs when iterating over lists of refs. Normally Git will try to include any such refs, which may cause some operations to fail. This is usually preferable, as potentially destructive operations (e.g., git- prune(1)) are better off aborting rather than ignoring broken refs (and thus considering the history they point to as not worth saving). The default value is 1 (i.e., be paranoid about detecting and aborting all operations). You should not normally need to set this to 0, but it may be useful when trying to salvage data from a corrupted repository.
GIT_COMMIT_GRAPH_PARANOIA When loading a commit object from the commit-graph, Git performs an existence check on the object in the object database. This is done to avoid issues with stale commit-graphs that contain references to already-deleted commits, but comes with a performance penalty.
The default is "false", which disables the aforementioned behavior. Setting this to "true" enables the existence check so that stale commits will never be returned from the commit-graph at the cost of performance.
GIT_ALLOW_PROTOCOL If set to a colon-separated list of protocols, behave as if protocol.allow is set to never, and each of the listed protocols has protocol.<name>.allow set to always (overriding any existing configuration). See the description of protocol.allow in git-config(1) for more details.
GIT_PROTOCOL_FROM_USER Set this Boolean environment variable to false to prevent protocols used by fetch/push/clone which are configured to the user state. This is useful to restrict recursive submodule initialization from an untrusted repository or for programs which feed potentially-untrusted URLS to git commands. See git-config(1) for more details.
GIT_PROTOCOL For internal use only. Used in handshaking the wire protocol. Contains a colon : separated list of keys with optional values <key>[=<value>]. Presence of unknown keys and values must be ignored.
Note that servers may need to be configured to allow this variable to pass over some transports. It will be propagated automatically when accessing local repositories (i.e., file:// or a filesystem path), as well as over the git:// protocol. For git-over-http, it should work automatically in most configurations, but see the discussion in git-http-backend(1). For git-over-ssh, the ssh server may need to be configured to allow clients to pass this variable (e.g., by using AcceptEnv GIT_PROTOCOL with OpenSSH).
This configuration is optional. If the variable is not propagated, then clients will fall back to the original "v0" protocol (but may miss out on some performance improvements or features). This variable currently only affects clones and fetches; it is not yet used for pushes (but may be in the future).
GIT_OPTIONAL_LOCKS If this Boolean environment variable is set to false, Git will complete any requested operation without performing any optional sub-operations that require taking a lock. For example, this will prevent git status from refreshing the index as a side effect. This is useful for processes running in the background which do not want to cause lock contention with other operations on the repository. Defaults to 1.
GIT_REDIRECT_STDIN, GIT_REDIRECT_STDOUT, GIT_REDIRECT_STDERR Windows-only: allow redirecting the standard input/output/error handles to paths specified by the environment variables. This is particularly useful in multi-threaded applications where the canonical way to pass standard handles via CreateProcess() is not an option because it would require the handles to be marked inheritable (and consequently every spawned process would inherit them, possibly blocking regular Git operations). The primary intended use case is to use named pipes for communication (e.g. \\.\pipe\my-git-stdin-123).
Two special values are supported: off will simply close the corresponding standard handle, and if GIT_REDIRECT_STDERR is 2>&1, standard error will be redirected to the same handle as standard output.
GIT_PRINT_SHA1_ELLIPSIS (deprecated) If set to yes, print an ellipsis following an (abbreviated) SHA-1 value. This affects indications of detached HEADs (git-checkout(1)) and the raw diff output (git-diff(1)). Printing an ellipsis in the cases mentioned is no longer considered adequate and support for it is likely to be removed in the foreseeable future (along with the variable).
GIT_ADVICE If set to 0, then disable all advice messages. These messages are intended to provide hints to human users that may help them get out of problematic situations or take advantage of new features. Users can disable individual messages using the advice.* config keys. These messages may be disruptive to tools that execute Git processes, so this variable is available to disable the messages. (The –no-advice global option is also available, but old Git versions may fail when this option is not understood. The environment variable will be ignored by Git versions that do not understand it.)
DISCUSSION More detail on the following is available from the Git concepts chapter of the user-manual[3] and gitcore-tutorial(7).
A Git project normally consists of a working directory with a ".git" subdirectory at the top level. The .git directory contains, among other things, a compressed object database representing the complete history of the project, an "index" file which links that history to the current contents of the working tree, and named pointers into that history such as tags and branch heads.
The object database contains objects of three main types: blobs, which hold file data; trees, which point to blobs and other trees to build up directory hierarchies; and commits, which each reference a single tree and some number of parent commits.
The commit, equivalent to what other systems call a "changeset" or "version", represents a step in the project’s history, and each parent represents an immediately preceding step. Commits with more than one parent represent merges of independent lines of development.
All objects are named by the SHA-1 hash of their contents, normally written as a string of 40 hex digits. Such names are globally unique. The entire history leading up to a commit can be vouched for by signing just that commit. A fourth object type, the tag, is provided for this purpose.
When first created, objects are stored in individual files, but for efficiency may later be compressed together into "pack files".
Named pointers called refs mark interesting points in history. A ref may contain the SHA-1 name of an object or the name of another ref (the latter is called a "symbolic ref"). Refs with names beginning refs/head/ contain the SHA-1 name of the most recent commit (or "head") of a branch under development. SHA-1 names of tags of interest are stored under refs/tags/. A symbolic ref named HEAD contains the name of the currently checked-out branch.
The index file is initialized with a list of all paths and, for each path, a blob object and a set of attributes. The blob object represents the contents of the file as of the head of the current branch. The attributes (last modified time, size, etc.) are taken from the corresponding file in the working tree. Subsequent changes to the working tree can be found by comparing these attributes. The index may be updated with new content, and new commits may be created from the content stored in the index.
The index is also capable of storing multiple entries (called "stages") for a given pathname. These stages are used to hold the various unmerged version of a file when a merge is in progress.
SECURITY Some configuration options and hook files may cause Git to run arbitrary shell commands. Because configuration and hooks are not copied using git clone, it is generally safe to clone remote repositories with untrusted content, inspect them with git log, and so on.
However, it is not safe to run Git commands in a .git directory (or the working tree that surrounds it) when that .git directory itself comes from an untrusted source. The commands in its config and hooks are executed in the usual way.
By default, Git will refuse to run when the repository is owned by someone other than the user running the command. See the entry for safe.directory in git-config(1). While this can help protect you in a multi-user environment, note that you can also acquire untrusted repositories that are owned by you (for example, if you extract a zip file or tarball from an untrusted source). In such cases, you’d need to "sanitize" the untrusted repository first.
If you have an untrusted .git directory, you should first clone it with git clone –no-local to obtain a clean copy. Git does restrict the set of options and hooks that will be run by upload-pack, which handles the server side of a clone or fetch, but beware that the surface area for attack against upload-pack is large, so this does carry some risk. The safest thing is to serve the repository as an unprivileged user (either via git- daemon(1), ssh, or using other tools to change user ids). See the discussion in the SECURITY section of git-upload-pack(1).
FURTHER DOCUMENTATION See the references in the "description" section to get started using Git. The following is probably more detail than necessary for a first-time user.
The Git concepts chapter of the user-manual[3] and gitcore-tutorial(7) both provide introductions to the underlying Git architecture.
See gitworkflows(7) for an overview of recommended workflows.
See also the howto[4] documents for some useful examples.
The internals are documented in the Git API documentation[5].
Users migrating from CVS may also want to read gitcvs-migration(7).
AUTHORS Git was started by Linus Torvalds, and is currently maintained by Junio C Hamano. Numerous contributions have come from the Git mailing list <git@vger.kernel.org[6]>. https://openhub.net/p/git/contributors/summary gives you a more complete list of contributors.
If you have a clone of git.git itself, the output of git-shortlog(1) and git-blame(1) can show you the authors for specific parts of the project.
REPORTING BUGS Report bugs to the Git mailing list <git@vger.kernel.org[6]> where the development and maintenance is primarily done. You do not have to be subscribed to the list to send a message there. See the list archive at https://lore.kernel.org/git for previous bug reports and other discussions.
Issues which are security relevant should be disclosed privately to the Git Security mailing list <git-security@googlegroups.com[7]>.
SEE ALSO gittutorial(7), gittutorial-2(7), giteveryday(7), gitcvs-migration(7), gitglossary(7), gitcore-tutorial(7), gitcli(7), The Git User’s Manual[1], gitworkflows(7)
GIT Part of the git(1) suite
NOTES 1. Git User’s Manual file:///usr/share/doc/git/user-manual.html
2. Trace2 documentation file:///usr/share/doc/git/technical/api-trace2.html
3. Git concepts chapter of the user-manual file:///usr/share/doc/git/user-manual.html#git-concepts
4. howto file:///usr/share/doc/git/howto-index.html
5. Git API documentation file:///usr/share/doc/git/technical/api-index.html
6. git@vger.kernel.org mailto:git@vger.kernel.org
7. git-security@googlegroups.com mailto:git-security@googlegroups.com
Git 2.47.3 06/13/2025 GIT(1)
Приложение: Справочная документация BASH
BASH(1) General Commands Manual BASH(1)
NAME bash – GNU Bourne-Again SHell
SYNOPSIS bash [options] [command_string | file]
COPYRIGHT Bash is Copyright (C) 1989-2020 by the Free Software Foundation, Inc.
DESCRIPTION Bash is an sh-compatible command language interpreter that executes commands read from the standard input or from a file. Bash also incorporates useful features from the Korn and C shells (ksh and csh).
Bash is intended to be a conformant implementation of the Shell and Utilities portion of the IEEE POSIX specification (IEEE Standard 1003.1). Bash can be configured to be POSIX-conformant by default.
OPTIONS All of the single-character shell options documented in the description of the set builtin command, including -o, can be used as options when the shell is invoked. In addition, bash interprets the following options when it is invoked:
–c If the -c option is present, then commands are read from the first non-option argument command_string. If there are arguments after the command_string, the first argument is assigned to $0 and any remaining arguments are assigned to the positional parameters. The assignment to $0 sets the name of the shell, which is used in warning and error messages. -i If the -i option is present, the shell is interactive. -l Make bash act as if it had been invoked as a login shell (see INVOCATION below). -r If the -r option is present, the shell becomes restricted (see RESTRICTED SHELL below). -s If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This op‐ tion allows the positional parameters to be set when invoking an interactive shell or when reading input through a pipe. -D A list of all double-quoted strings preceded by $ is printed on the standard output. These are the strings that are subject to language translation when the current locale is not C or POSIX. This implies the -n option; no commands will be executed. [-+]O [shopt_option] shopt_option is one of the shell options accepted by the shopt builtin (see SHELL BUILTIN COMMANDS below). If shopt_option is present, -O sets the value of that option; +O unsets it. If shopt_option is not supplied, the names and values of the shell options accepted by shopt are printed on the standard output. If the invocation option is +O, the output is displayed in a format that may be reused as input. – A – signals the end of options and disables further option processing. Any arguments after the – are treated as filenames and arguments. An argument of – is equivalent to –.
Bash also interprets a number of multi-character options. These options must appear on the command line before the single-character options to be recognized.
–-debugger Arrange for the debugger profile to be executed before the shell starts. Turns on extended debugging mode (see the description of the extde‐ bug option to the shopt builtin below). –dump-po-strings Equivalent to -D, but the output is in the GNU gettext po (portable object) file format. –dump-strings Equivalent to -D. –help Display a usage message on standard output and exit successfully. –init-file file –rcfile file Execute commands from file instead of the standard personal initialization file ~/.bashrc if the shell is interactive (see INVOCATION below).
–-login Equivalent to -l.
–-noediting Do not use the GNU readline library to read command lines when the shell is interactive.
–-noprofile Do not read either the system-wide startup file /etc/profile or any of the personal initialization files ~/.bash_profile, ~/.bash_login, or ~/.profile. By default, bash reads these files when it is invoked as a login shell (see INVOCATION below).
–-norc Do not read and execute the personal initialization file ~/.bashrc if the shell is interactive. This option is on by default if the shell is invoked as sh.
–-posix Change the behavior of bash where the default operation differs from the POSIX standard to match the standard (posix mode). See SEE ALSO be‐ low for a reference to a document that details how posix mode affects bash's behavior.
–-restricted The shell becomes restricted (see RESTRICTED SHELL below).
–-rpm-requires Produce the list of files that are required for the shell script to run. This implies '-n' and is subject to the same limitations as compile time error checking checking; Command substitutions, Conditional expressions and eval builtin are not parsed so some dependencies may be missed.
–-verbose Equivalent to -v.
–-version Show version information for this instance of bash on the standard output and exit successfully.
ARGUMENTS If arguments remain after option processing, and neither the -c nor the -s option has been supplied, the first argument is assumed to be the name of a file containing shell commands. If bash is invoked in this fashion, $0 is set to the name of the file, and the positional parameters are set to the remaining arguments. Bash reads and executes commands from this file, then exits. Bash's exit status is the exit status of the last command ex‐ ecuted in the script. If no commands are executed, the exit status is 0. An attempt is first made to open the file in the current directory, and, if no file is found, then the shell searches the directories in PATH for the script.
INVOCATION A login shell is one whose first character of argument zero is a -, or one started with the –login option.
An interactive shell is one started without non-option arguments (unless -s is specified) and without the -c option whose standard input and error are both connected to terminals (as determined by isatty(3)), or one started with the -i option. PS1 is set and $– includes i if bash is interac‐ tive, allowing a shell script or a startup file to test this state.
The following paragraphs describe how bash executes its startup files. If any of the files exist but cannot be read, bash reports an error. Tildes are expanded in filenames as described below under Tilde Expansion in the EXPANSION section.
When bash is invoked as an interactive login shell, or as a non-interactive shell with the –login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The –noprofile option may be used when the shell is started to inhibit this behavior.
When an interactive login shell exits, or a non-interactive login shell executes the exit builtin command, bash reads and executes commands from the files ~/.bash_logout and /etc/bash.bash_logout, if the files exists.
When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the –norc option. The –rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc.
When bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed: if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi but the value of the PATH variable is not used to search for the filename.
If bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well. When invoked as an interactive login shell, or a non-interactive shell with the –login option, it first attempts to read and execute commands from /etc/profile and ~/.profile, in that order. The –noprofile option may be used to inhibit this behavior. When in‐ voked as an interactive shell with the name sh, bash looks for the variable ENV, expands its value if it is defined, and uses the expanded value as the name of a file to read and execute. Since a shell invoked as sh does not attempt to read and execute commands from any other startup files, the –rcfile option has no effect. A non-interactive shell invoked with the name sh does not attempt to read any other startup files. When invoked as sh, bash enters posix mode after the startup files are read.
When bash is started in posix mode, as with the –posix command line option, it follows the POSIX standard for startup files. In this mode, interac‐ tive shells expand the ENV variable and commands are read and executed from the file whose name is the expanded value. No other startup files are read.
Bash attempts to determine when it is being run with its standard input connected to a network connection, as when executed by the remote shell dae‐ mon, usually rshd, or the secure shell daemon sshd. If bash determines it is being run in this fashion, it reads and executes commands from ~/.bashrc, if that file exists and is readable. It will not do this if invoked as sh. The –norc option may be used to inhibit this behavior, and the –rcfile option may be used to force another file to be read, but neither rshd nor sshd generally invoke the shell with those options or allow them to be specified.
If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, no startup files are read, shell functions are not inherited from the environment, the SHELLOPTS, BASHOPTS, CDPATH, and GLOBIGNORE variables, if they appear in the environment, are ignored, and the effective user id is set to the real user id. If the -p option is supplied at invocation, the startup behavior is the same, but the effective user id is not reset.
DEFINITIONS The following definitions are used throughout the rest of this document. blank A space or tab. word A sequence of characters considered as a single unit by the shell. Also known as a token. name A word consisting only of alphanumeric characters and underscores, and beginning with an alphabetic character or an underscore. Also referred to as an identifier. metacharacter A character that, when unquoted, separates words. One of the following: | & ; ( ) < > space tab newline control operator A token that performs a control function. It is one of the following symbols: || & && ; ;; ;& ;;& ( ) | |& <newline>
RESERVED WORDS Reserved words are words that have a special meaning to the shell. The following words are recognized as reserved when unquoted and either the first word of a command (see SHELL GRAMMAR below), the third word of a case or select command (only in is valid), or the third word of a for command (only in and do are valid):
! case coproc do done elif else esac fi for function if in select then until while { } time [[ ]]
SHELL GRAMMAR Simple Commands A simple command is a sequence of optional variable assignments followed by blank-separated words and redirections, and terminated by a control oper‐ ator. The first word specifies the command to be executed, and is passed as argument zero. The remaining words are passed as arguments to the in‐ voked command.
The return value of a simple command is its exit status, or 128+n if the command is terminated by signal n.
Pipelines A pipeline is a sequence of one or more commands separated by one of the control operators | or |&. The format for a pipeline is:
[time [-p]] [ ! ] command [ [|⎪|&] command2 … ]
The standard output of command is connected via a pipe to the standard input of command2. This connection is performed before any redirections spec‐ ified by the command (see REDIRECTION below). If |& is used, command's standard error, in addition to its standard output, is connected to com‐ mand2's standard input through the pipe; it is shorthand for 2>&1 |. This implicit redirection of the standard error to the standard output is per‐ formed after any redirections specified by the command.
The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. If pipefail is enabled, the pipe‐ line's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully. If the reserved word ! precedes a pipeline, the exit status of that pipeline is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value.
If the time reserved word precedes a pipeline, the elapsed as well as user and system time consumed by its execution are reported when the pipeline terminates. The -p option changes the output format to that specified by POSIX. When the shell is in posix mode, it does not recognize time as a reserved word if the next token begins with a `-'. The TIMEFORMAT variable may be set to a format string that specifies how the timing information should be displayed; see the description of TIMEFORMAT under Shell Variables below.
When the shell is in posix mode, time may be followed by a newline. In this case, the shell displays the total user and system time consumed by the shell and its children. The TIMEFORMAT variable may be used to specify the format of the time information.
Each command in a pipeline is executed as a separate process (i.e., in a subshell). See COMMAND EXECUTION ENVIRONMENT for a description of a sub‐ shell environment. If the lastpipe option is enabled using the shopt builtin (see the description of shopt below), the last element of a pipeline may be run by the shell process.
Lists A list is a sequence of one or more pipelines separated by one of the operators ;, &, &&, or ||, and optionally terminated by one of ;, &, or <new‐ line>.
Of these list operators, && and || have equal precedence, followed by ; and &, which have equal precedence.
A sequence of one or more newlines may appear in a list instead of a semicolon to delimit commands.
If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0. These are referred to as asynchronous commands. Commands separated by a ; are executed sequen‐ tially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed.
AND and OR lists are sequences of one or more pipelines separated by the && and || control operators, respectively. AND and OR lists are executed with left associativity. An AND list has the form
command1 && command2
command2 is executed if, and only if, command1 returns an exit status of zero (success).
An OR list has the form
command1 || command2
command2 is executed if, and only if, command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list.
Compound Commands A compound command is one of the following. In most cases a list in a command's description may be separated from the rest of the command by one or more newlines, and may be followed by a newline in place of a semicolon.
(list) list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below). Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list.
{ list; } list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. This is known as a group com‐ mand. The return status is the exit status of list. Note that unlike the metacharacters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recognized. Since they do not cause a word break, they must be separated from list by whitespace or another shell metacharacter.
((expression)) The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to let "expression".
[[ expression ]] Return a status of 0 or 1 depending on the evaluation of the conditional expression expression. Expressions are composed of the primaries de‐ scribed below under CONDITIONAL EXPRESSIONS. Word splitting and pathname expansion are not performed on the words between the [[ and ]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed. Conditional operators such as -f must be unquoted to be recognized as primaries.
When used with [[, the < and > operators sort lexicographically using the current locale.
When the == and != operators are used, the string to the right of the operator is considered a pattern and matched according to the rules de‐ scribed below under Pattern Matching, as if the extglob shell option were enabled. The = operator is equivalent to ==. If the nocasematch shell option is enabled, the match is performed without regard to the case of alphabetic characters. The return value is 0 if the string matches (==) or does not match (!=) the pattern, and 1 otherwise. Any part of the pattern may be quoted to force the quoted portion to be matched as a string.
An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the oper‐ ator is considered a POSIX extended regular expression and matched accordingly (using the POSIX regcomp and regexec interfaces usually de‐ scribed in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the nocasematch shell option is enabled, the match is performed without regard to the case of alphabetic characters. Any part of the pattern may be quoted to force the quoted portion to be matched as a string. Bracket expressions in regular expressions must be treated carefully, since normal quoting characters lose their meanings between brackets. If the pattern is stored in a shell variable, quoting the variable expansion forces the entire pattern to be matched as a string.
The pattern will match if it matches any part of the string. Anchor the pattern using the ^ and $ regular expression operators to force it to match the entire string. The array variable BASH_REMATCH records which parts of the string matched the pattern. The element of BASH_REMATCH with index 0 contains the portion of the string matching the entire regular expression. Substrings matched by parenthesized subexpressions within the regular expression are saved in the remaining BASH_REMATCH indices. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.
Expressions may be combined using the following operators, listed in decreasing order of precedence:
( expression ) Returns the value of expression. This may be used to override the normal precedence of operators. ! expression True if expression is false. expression1 && expression2 True if both expression1 and expression2 are true. expression1 || expression2 True if either expression1 or expression2 is true.
The && and || operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire con‐ ditional expression.
for name [ [ in [ word … ] ] ; ] do list ; done The list of words following in is expanded, generating a list of items. The variable name is set to each element of this list in turn, and list is executed each time. If the in word is omitted, the for command executes list once for each positional parameter that is set (see PA‐ RAMETERS below). The return status is the exit status of the last command that executes. If the expansion of the items following in results in an empty list, no commands are executed, and the return status is 0.
for (( expr1 ; expr2 ; expr3 )) ; do list ; done First, the arithmetic expression expr1 is evaluated according to the rules described below under ARITHMETIC EVALUATION. The arithmetic ex‐ pression expr2 is then evaluated repeatedly until it evaluates to zero. Each time expr2 evaluates to a non-zero value, list is executed and the arithmetic expression expr3 is evaluated. If any expression is omitted, it behaves as if it evaluates to 1. The return value is the exit status of the last command in list that is executed, or false if any of the expressions is invalid.
select name [ in word ] ; do list ; done The list of words following in is expanded, generating a list of items. The set of expanded words is printed on the standard error, each pre‐ ceded by a number. If the in word is omitted, the positional parameters are printed (see PARAMETERS below). The PS3 prompt is then displayed and a line read from the standard input. If the line consists of a number corresponding to one of the displayed words, then the value of name is set to that word. If the line is empty, the words and prompt are displayed again. If EOF is read, the command completes. Any other value read causes name to be set to null. The line read is saved in the variable REPLY. The list is executed after each selection until a break command is executed. The exit status of select is the exit status of the last command executed in list, or zero if no commands were executed.
case word in [ [(] pattern [ | pattern ] … ) list ;; ] … esac A case command first expands word, and tries to match it against each pattern in turn, using the matching rules described under Pattern Match‐ ing below. The word is expanded using tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution and quote removal. Each pattern examined is expanded using tilde expansion, parameter and variable expansion, arithmetic expan‐ sion, command substitution, and process substitution. If the nocasematch shell option is enabled, the match is performed without regard to the case of alphabetic characters. When a match is found, the corresponding list is executed. If the ;; operator is used, no subsequent matches are attempted after the first pattern match. Using ;& in place of ;; causes execution to continue with the list associated with the next set of patterns. Using ;;& in place of ;; causes the shell to test the next pattern list in the statement, if any, and execute any asso‐ ciated list on a successful match, continuing the case statement execution as if the pattern list had not matched. The exit status is zero if no pattern matches. Otherwise, it is the exit status of the last command executed in list.
if list; then list; [ elif list; then list; ] … [ else list; ] fi The if list is executed. If its exit status is zero, the then list is executed. Otherwise, each elif list is executed in turn, and if its exit status is zero, the corresponding then list is executed and the command completes. Otherwise, the else list is executed, if present. The exit status is the exit status of the last command executed, or zero if no condition tested true.
while list-1; do list-2; done until list-1; do list-2; done The while command continuously executes the list list-2 as long as the last command in the list list-1 returns an exit status of zero. The until command is identical to the while command, except that the test is negated: list-2 is executed as long as the last command in list-1 re‐ turns a non-zero exit status. The exit status of the while and until commands is the exit status of the last command executed in list-2, or zero if none was executed.
Coprocesses A coprocess is a shell command preceded by the coproc reserved word. A coprocess is executed asynchronously in a subshell, as if the command had been terminated with the & control operator, with a two-way pipe established between the executing shell and the coprocess.
The format for a coprocess is:
coproc [NAME] command [redirections]
This creates a coprocess named NAME. If NAME is not supplied, the default name is COPROC. NAME must not be supplied if command is a simple command (see above); otherwise, it is interpreted as the first word of the simple command. When the coprocess is executed, the shell creates an array vari‐ able (see Arrays below) named NAME in the context of the executing shell. The standard output of command is connected via a pipe to a file descrip‐ tor in the executing shell, and that file descriptor is assigned to NAME[0]. The standard input of command is connected via a pipe to a file de‐ scriptor in the executing shell, and that file descriptor is assigned to NAME[1]. This pipe is established before any redirections specified by the command (see REDIRECTION below). The file descriptors can be utilized as arguments to shell commands and redirections using standard word expan‐ sions. Other than those created to execute command and process substitutions, the file descriptors are not available in subshells. The process ID of the shell spawned to execute the coprocess is available as the value of the variable NAME_PID. The wait builtin command may be used to wait for the coprocess to terminate.
Since the coprocess is created as an asynchronous command, the coproc command always returns success. The return status of a coprocess is the exit status of command.
Shell Function Definitions A shell function is an object that is called like a simple command and executes a compound command with a new set of positional parameters. Shell functions are declared as follows:
fname () compound-command [redirection] function fname [()] compound-command [redirection] This defines a function named fname. The reserved word function is optional. If the function reserved word is supplied, the parentheses are optional. The body of the function is the compound command compound-command (see Compound Commands above). That command is usually a list of commands between { and }, but may be any command listed under Compound Commands above, with one exception: If the function reserved word is used, but the parentheses are not supplied, the braces are required. compound-command is executed whenever fname is specified as the name of a simple command. When in posix mode, fname must be a valid shell name and may not be the name of one of the POSIX special builtins. In de‐ fault mode, a function name can be any unquoted shell word that does not contain $. Any redirections (see REDIRECTION below) specified when a function is defined are performed when the function is executed. The exit status of a function definition is zero unless a syntax error oc‐ curs or a readonly function with the same name already exists. When executed, the exit status of a function is the exit status of the last command executed in the body. (See FUNCTIONS below.)
COMMENTS In a non-interactive shell, or an interactive shell in which the interactive_comments option to the shopt builtin is enabled (see SHELL BUILTIN COM‐ MANDS below), a word beginning with # causes that word and all remaining characters on that line to be ignored. An interactive shell without the in‐ teractive_comments option enabled does not allow comments. The interactive_comments option is on by default in interactive shells.
QUOTING Quoting is used to remove the special meaning of certain characters or words to the shell. Quoting can be used to disable special treatment for spe‐ cial characters, to prevent reserved words from being recognized as such, and to prevent parameter expansion.
Each of the metacharacters listed above under DEFINITIONS has special meaning to the shell and must be quoted if it is to represent itself.
When the command history expansion facilities are being used (see HISTORY EXPANSION below), the history expansion character, usually !, must be quoted to prevent history expansion.
There are three quoting mechanisms: the escape character, single quotes, and double quotes.
A non-quoted backslash (\) is the escape character. It preserves the literal value of the next character that follows, with the exception of <new‐ line>. If a \<newline> pair appears, and the backslash is not itself quoted, the \<newline> is treated as a line continuation (that is, it is re‐ moved from the input stream and effectively ignored).
Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.
Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when his‐ tory expansion is enabled, !. When the shell is in posix mode, the ! has no special meaning within double quotes, even when history expansion is en‐ abled. The characters $ and ` retain their special meaning within double quotes. The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or <newline>. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.
The special parameters * and @ have special meaning when in double quotes (see PARAMETERS below).
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows: \a alert (bell) \b backspace \e \E an escape character \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \\ backslash \' single quote \" double quote \? question mark \nnn the eight-bit character whose value is the octal value nnn (one to three octal digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) \uHHHH the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits) \UHHHHHHHH the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits) \cx a control-x character
The expanded result is single-quoted, as if the dollar sign had not been present.
A double-quoted string preceded by a dollar sign ($"string") will cause the string to be translated according to the current locale. The gettext in‐ frastructure performs the message catalog lookup and translation, using the LC_MESSAGES and TEXTDOMAIN shell variables. If the current locale is C or POSIX, or if there are no translations available, the dollar sign is ignored. If the string is translated and replaced, the replacement is dou‐ ble-quoted.
PARAMETERS A parameter is an entity that stores values. It can be a name, a number, or one of the special characters listed below under Special Parameters. A variable is a parameter denoted by a name. A variable has a value and zero or more attributes. Attributes are assigned using the declare builtin command (see declare below in SHELL BUILTIN COMMANDS).
A parameter is set if it has been assigned a value. The null string is a valid value. Once a variable is set, it may be unset only by using the un‐ set builtin command (see SHELL BUILTIN COMMANDS below).
A variable may be assigned to by a statement of the form
name=[value]
If value is not given, the variable is assigned the null string. All values undergo tilde expansion, parameter and variable expansion, command sub‐ stitution, arithmetic expansion, and quote removal (see EXPANSION below). If the variable has its integer attribute set, then value is evaluated as an arithmetic expression even if the $((…)) expansion is not used (see Arithmetic Expansion below). Word splitting is not performed, with the ex‐ ception of "$@" as explained below under Special Parameters. Pathname expansion is not performed. Assignment statements may also appear as argu‐ ments to the alias, declare, typeset, export, readonly, and local builtin commands (declaration commands). When in posix mode, these builtins may appear in a command after one or more instances of the command builtin and retain these assignment statement properties.
In the context where an assignment statement is assigning a value to a shell variable or array index, the += operator can be used to append to or add to the variable's previous value. This includes arguments to builtin commands such as declare that accept assignment statements (declaration com‐ mands). When += is applied to a variable for which the integer attribute has been set, value is evaluated as an arithmetic expression and added to the variable's current value, which is also evaluated. When += is applied to an array variable using compound assignment (see Arrays below), the variable's value is not unset (as it is when using =), and new values are appended to the array beginning at one greater than the array's maximum in‐ dex (for indexed arrays) or added as additional key-value pairs in an associative array. When applied to a string-valued variable, value is expanded and appended to the variable's value.
A variable can be assigned the nameref attribute using the -n option to the declare or local builtin commands (see the descriptions of declare and local below) to create a nameref, or a reference to another variable. This allows variables to be manipulated indirectly. Whenever the nameref variable is referenced, assigned to, unset, or has its attributes modified (other than using or changing the nameref attribute itself), the operation is actually performed on the variable specified by the nameref variable's value. A nameref is commonly used within shell functions to refer to a variable whose name is passed as an argument to the function. For instance, if a variable name is passed to a shell function as its first argument, running declare -n ref=$1 inside the function creates a nameref variable ref whose value is the variable name passed as the first argument. References and assignments to ref, and changes to its attributes, are treated as references, assignments, and attribute modifications to the variable whose name was passed as $1. If the control variable in a for loop has the nameref attribute, the list of words can be a list of shell variables, and a name reference will be estab‐ lished for each word in the list, in turn, when the loop is executed. Array variables cannot be given the nameref attribute. However, nameref vari‐ ables can reference array variables and subscripted array variables. Namerefs can be unset using the -n option to the unset builtin. Otherwise, if unset is executed with the name of a nameref variable as an argument, the variable referenced by the nameref variable will be unset.
Positional Parameters A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell's arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameters may not be assigned to with assign‐ ment statements. The positional parameters are temporarily replaced when a shell function is executed (see FUNCTIONS below).
When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces (see EXPANSION below).
Special Parameters The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. * Expands to the positional parameters, starting from one. When the expansion is not within double quotes, each positional parameter expands to a separate word. In contexts where it is performed, those words are subject to further word splitting and pathname expansion. When the ex‐ pansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c…", where c is the first character of the value of the IFS variable. If IFS is un‐ set, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators. @ Expands to the positional parameters, starting from one. In contexts where word splitting is performed, this expands each positional parame‐ ter to a separate word; if not within double quotes, these words are subject to word splitting. In contexts where word splitting is not per‐ formed, this expands to a single word with each positional parameter separated by a space. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" … If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed). # Expands to the number of positional parameters in decimal. ? Expands to the exit status of the most recently executed foreground pipeline. – Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option). $ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell. ! Expands to the process ID of the job most recently placed into the background, whether executed as an asynchronous command or using the bg builtin (see JOB CONTROL below). 0 Expands to the name of the shell or shell script. This is set at shell initialization. If bash is invoked with a file of commands, $0 is set
to the name of that file. If bash is started with the -c option, then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the filename used to invoke bash, as given by argument zero.
Shell Variables The following variables are set by the shell:
_ At shell startup, set to the pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous simple command executed in the foreground, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file currently being checked. BASH Expands to the full filename used to invoke this instance of bash. BASHOPTS A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -s option to the shopt builtin command (see SHELL BUILTIN COMMANDS below). The options appearing in BASHOPTS are those reported as on by shopt. If this variable is in the environ‐ ment when bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is read-only. BASHPID Expands to the process ID of the current bash process. This differs from $$ under certain circumstances, such as subshells that do not re‐ quire bash to be re-initialized. Assignments to BASHPID have no effect. If BASHPID is unset, it loses its special properties, even if it is subsequently reset. BASH_ALIASES An associative array variable whose members correspond to the internal list of aliases as maintained by the alias builtin. Elements added to this array appear in the alias list; however, unsetting array elements currently does not cause aliases to be removed from the alias list. If BASH_ALIASES is unset, it loses its special properties, even if it is subsequently reset. BASH_ARGC An array variable whose values are the number of parameters in each frame of the current bash execution call stack. The number of parameters to the current subroutine (shell function or script executed with . or source) is at the top of the stack. When a subroutine is executed, the number of parameters passed is pushed onto BASH_ARGC. The shell sets BASH_ARGC only when in extended debugging mode (see the description of
the extdebug option to the shopt builtin below). Setting extdebug after the shell has started to execute a script, or referencing this vari‐ able when extdebug is not set, may result in inconsistent values. BASH_ARGV An array variable containing all of the parameters in the current bash execution call stack. The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto BASH_ARGV. The shell sets BASH_ARGV only when in extended debugging mode (see the description of the extdebug option to the shopt builtin below). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values. BASH_ARGV0 When referenced, this variable expands to the name of the shell or shell script (identical to $0; see the description of special parameter 0 above). Assignment to BASH_ARGV0 causes the value assigned to also be assigned to $0. If BASH_ARGV0 is unset, it loses its special proper‐ ties, even if it is subsequently reset. BASH_CMDS An associative array variable whose members correspond to the internal hash table of commands as maintained by the hash builtin. Elements added to this array appear in the hash table; however, unsetting array elements currently does not cause command names to be removed from the hash table. If BASH_CMDS is unset, it loses its special properties, even if it is subsequently reset. BASH_COMMAND The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap. If BASH_COMMAND is unset, it loses its special properties, even if it is subsequently reset. BASH_EXECUTION_STRING
The command argument to the -c invocation option. BASH_LINENO An array variable whose members are the line numbers in source files where each corresponding member of FUNCNAME was invoked. ${BASH_LINENO[$i]} is the line number in the source file (${BASH_SOURCE[$i+1]}) where ${FUNCNAME[$i]} was called (or ${BASH_LINENO[$i-1]} if referenced within another shell function). Use LINENO to obtain the current line number. BASH_LOADABLES_PATH A colon-separated list of directories in which the shell looks for dynamically loadable builtins specified by the enable command. BASH_REMATCH An array variable whose members are assigned by the =~ binary operator to the [[ conditional command. The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the nth parenthesized subexpression. BASH_SOURCE An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are de‐ fined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}. BASH_SUBSHELL Incremented by one within each subshell or subshell environment when the shell begins executing in that environment. The initial value is 0. If BASH_SUBSHELL is unset, it loses its special properties, even if it is subsequently reset. BASH_VERSINFO A readonly array variable whose members hold version information for this instance of bash. The values assigned to the array members are as follows: BASH_VERSINFO[0] The major version number (the release).
BASH_VERSINFO[1] The minor version number (the version). BASH_VERSINFO[2] The patch level. BASH_VERSINFO[3] The build version. BASH_VERSINFO[4] The release status (e.g., beta1). BASH_VERSINFO[5] The value of MACHTYPE. BASH_VERSION Expands to a string describing the version of this instance of bash. COMP_CWORD An index into ${COMP_WORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion below). COMP_KEY The key (or final key of a key sequence) used to invoke the current completion function. COMP_LINE The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion fa‐ cilities (see Programmable Completion below). COMP_POINT The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the current command, the value of this variable is equal to ${#COMP_LINE}. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion below). COMP_TYPE Set to an integer value corresponding to the type of completion attempted that caused a completion function to be called: TAB, for normal com‐
pletion, ?, for listing completions after successive tabs, !, for listing alternatives on partial word completion, @, to list completions if the word is not unmodified, or %, for menu completion. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion below). COMP_WORDBREAKS The set of characters that the readline library treats as word separators when performing word completion. If COMP_WORDBREAKS is unset, it loses its special properties, even if it is subsequently reset. COMP_WORDS An array variable (see Arrays below) consisting of the individual words in the current command line. The line is split into words as readline would split it, using COMP_WORDBREAKS as described above. This variable is available only in shell functions invoked by the programmable com‐ pletion facilities (see Programmable Completion below). COPROC An array variable (see Arrays below) created to hold the file descriptors for output from and input to an unnamed coprocess (see Coprocesses above). DIRSTACK An array variable (see Arrays below) containing the current contents of the directory stack. Directories appear in the stack in the order they are displayed by the dirs builtin. Assigning to members of this array variable may be used to modify directories already in the stack, but the pushd and popd builtins must be used to add and remove directories. Assignment to this variable will not change the current direc‐ tory. If DIRSTACK is unset, it loses its special properties, even if it is subsequently reset. EPOCHREALTIME Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch (see time(3)) as a floating point value with micro-second granularity. Assignments to EPOCHREALTIME are ignored. If EPOCHREALTIME is unset, it loses its special properties, even if it is subsequently reset.
EPOCHSECONDS Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch (see time(3)). Assignments to EPOCHSECONDS are ignored. If EPOCHSECONDS is unset, it loses its special properties, even if it is subsequently reset. EUID Expands to the effective user ID of the current user, initialized at shell startup. This variable is readonly. FUNCNAME An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is "main". This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset.
This variable can be used with BASH_LINENO and BASH_SOURCE. Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]}. The caller builtin displays the current call stack using this information. GROUPS An array variable containing the list of groups of which the current user is a member. Assignments to GROUPS have no effect. If GROUPS is unset, it loses its special properties, even if it is subsequently reset. HISTCMD The history number, or index in the history list, of the current command. Assignments to HISTCMD are ignored. If HISTCMD is unset, it loses its special properties, even if it is subsequently reset. HOSTNAME Automatically set to the name of the current host. HOSTTYPE Automatically set to a string that uniquely describes the type of machine on which bash is executing. The default is system-dependent. LINENO Each time this parameter is referenced, the shell substitutes a decimal number representing the current sequential line number (starting with 1) within a script or function. When not in a script or function, the value substituted is not guaranteed to be meaningful. If LINENO is un‐ set, it loses its special properties, even if it is subsequently reset. MACHTYPE Automatically set to a string that fully describes the system type on which bash is executing, in the standard GNU cpu-company-system format. The default is system-dependent. MAPFILE An array variable (see Arrays below) created to hold the text read by the mapfile builtin when no variable name is supplied. OLDPWD The previous working directory as set by the cd command.
OPTARG The value of the last option argument processed by the getopts builtin command (see SHELL BUILTIN COMMANDS below). OPTIND The index of the next argument to be processed by the getopts builtin command (see SHELL BUILTIN COMMANDS below). OSTYPE Automatically set to a string that describes the operating system on which bash is executing. The default is system-dependent. PIPESTATUS An array variable (see Arrays below) containing a list of exit status values from the processes in the most-recently-executed foreground pipe‐ line (which may contain only a single command). PPID The process ID of the shell's parent. This variable is readonly. PWD The current working directory as set by the cd command. RANDOM Each time this parameter is referenced, it expands to a random integer between 0 and 32767. Assigning a value to RANDOM initializes (seeds) the sequence of random numbers. If RANDOM is unset, it loses its special properties, even if it is subsequently reset. READLINE_LINE The contents of the readline line buffer, for use with "bind -x" (see SHELL BUILTIN COMMANDS below). READLINE_MARK The position of the mark (saved insertion point) in the readline line buffer, for use with "bind -x" (see SHELL BUILTIN COMMANDS below). The characters between the insertion point and the mark are often called the region. READLINE_POINT The position of the insertion point in the readline line buffer, for use with "bind -x" (see SHELL BUILTIN COMMANDS below). REPLY Set to the line of input read by the read builtin command when no arguments are supplied. SECONDS Each time this parameter is referenced, the number of seconds since shell invocation is returned. If a value is assigned to SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value assigned. The number of seconds at
shell invocation and the current time is always determined by querying the system clock. If SECONDS is unset, it loses its special proper‐ ties, even if it is subsequently reset. SHELLOPTS A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -o option to the set builtin command (see SHELL BUILTIN COMMANDS below). The options appearing in SHELLOPTS are those reported as on by set -o. If this variable is in the environment when bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is read-only. SHLVL Incremented by one each time an instance of bash is started. SRANDOM This variable expands to a 32-bit pseudo-random number each time it is referenced. The random number generator is not linear on systems that support /dev/urandom or arc4random, so each returned number has no relationship to the numbers preceding it. The random number generator can‐ not be seeded, so assignments to this variable have no effect. If SRANDOM is unset, it loses its special properties, even if it is subse‐ quently reset. UID Expands to the user ID of the current user, initialized at shell startup. This variable is readonly.
The following variables are used by the shell. In some cases, bash assigns a default value to a variable; these cases are noted below.
BASH_COMPAT The value is used to set the shell's compatibility level. See SHELL COMPATIBILITY MODE below for a description of the various compatibility levels and their effects. The value may be a decimal number (e.g., 4.2) or an integer (e.g., 42) corresponding to the desired compatibility level. If BASH_COMPAT is unset or set to the empty string, the compatibility level is set to the default for the current version. If BASH_COMPAT is set to a value that is not one of the valid compatibility levels, the shell prints an error message and sets the compatibility level to the default for the current version. The valid values correspond to the compatibility levels described below under BSHELLCOMPATIBIL‐ ITYMODE. For example, 4.2 and 42 are valid values that correspond to the compat42 shopt option and set the compatibility level to 42. The current version is also a valid value. BASH_ENV If this parameter is set when bash is executing a shell script, its value is interpreted as a filename containing commands to initialize the shell, as in ~/.bashrc. The value of BASH_ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before be‐ ing interpreted as a filename. PATH is not used to search for the resultant filename. BASH_XTRACEFD If set to an integer corresponding to a valid file descriptor, bash will write the trace output generated when set -x is enabled to that file descriptor. The file descriptor is closed when BASH_XTRACEFD is unset or assigned a new value. Unsetting BASH_XTRACEFD or assigning it the empty string causes the trace output to be sent to the standard error. Note that setting BASH_XTRACEFD to 2 (the standard error file descrip‐ tor) and then unsetting it will result in the standard error being closed. CDPATH The search path for the cd command. This is a colon-separated list of directories in which the shell looks for destination directories speci‐ fied by the cd command. A sample value is ".:~:/usr". CHILD_MAX Set the number of exited child status values for the shell to remember. Bash will not allow this value to be decreased below a POSIX-mandated
minimum, and there is a maximum value (currently 8192) that this may not exceed. The minimum value is system-dependent. COLUMNS Used by the select compound command to determine the terminal width when printing selection lists. Automatically set if the checkwinsize op‐ tion is enabled or in an interactive shell upon receipt of a SIGWINCH. COMPREPLY An array variable from which bash reads the possible completions generated by a shell function invoked by the programmable completion facility (see Programmable Completion below). Each array element contains one possible completion. EMACS If bash finds this variable in the environment when the shell starts with value "t", it assumes that the shell is running in an Emacs shell buffer and disables line editing. ENV Expanded and executed similarly to BASH_ENV (see INVOCATION above) when an interactive shell is invoked in posix mode. EXECIGNORE A colon-separated list of shell patterns (see Pattern Matching) defining the list of filenames to be ignored by command search using PATH. Files whose full pathnames match one of these patterns are not considered executable files for the purposes of completion and command execu‐ tion via PATH lookup. This does not affect the behavior of the [, test, and [[ commands. Full pathnames in the command hash table are not subject to EXECIGNORE. Use this variable to ignore shared library files that have the executable bit set, but are not executable files. The pattern matching honors the setting of the extglob shell option. FCEDIT The default editor for the fc builtin command. FIGNORE A colon-separated list of suffixes to ignore when performing filename completion (see READLINE below). A filename whose suffix matches one of the entries in FIGNORE is excluded from the list of matched filenames. A sample value is ".o:~". FUNCNEST
If set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed this nesting level will cause the current command to abort. GLOBIGNORE A colon-separated list of patterns defining the set of file names to be ignored by pathname expansion. If a file name matched by a pathname expansion pattern also matches one of the patterns in GLOBIGNORE, it is removed from the list of matches. HISTCONTROL A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ignorespace, lines which begin with a space character are not saved in the history list. A value of ignoredups causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A value of erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIG‐ NORE. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL. HISTFILE The name of the file in which command history is saved (see HISTORY below). The default value is ~/.bash_history. If unset, the command his‐ tory is not saved when a shell exits. HISTFILESIZE The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if neces‐ sary, to contain no more than that number of lines by removing the oldest entries. The history file is also truncated to this size after writing it when a shell exits. If the value is 0, the history file is truncated to zero size. Non-numeric values and numeric values less than zero inhibit truncation. The shell sets the default value to the value of HISTSIZE after reading any startup files.
HISTIGNORE A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must match the complete line (no implicit `*' is appended). Each pattern is tested against the line after the checks specified by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, `&' matches the previous history line. `&' may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi- line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE. The pattern matching honors the setting of the extglob shell option. HISTSIZE The number of commands to remember in the command history (see HISTORY below). If the value is 0, commands are not saved in the history list. Numeric values less than zero result in every command being saved on the history list (there is no limit). The shell sets the default value to 500 after reading any startup files. HISTTIMEFORMAT If this variable is set and not null, its value is used as a format string for strftime(3) to print the time stamp associated with each his‐ tory entry displayed by the history builtin. If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines. HOME The home directory of the current user; the default argument for the cd builtin command. The value of this variable is also used when per‐ forming tilde expansion. HOSTFILE Contains the name of a file in the same format as /etc/hosts that should be read when the shell needs to complete a hostname. The list of possible hostname completions may be changed while the shell is running; the next time hostname completion is attempted after the value is changed, bash adds the contents of the new file to the existing list. If HOSTFILE is set, but has no value, or does not name a readable file,
bash attempts to read /etc/hosts to obtain the list of possible hostname completions. When HOSTFILE is unset, the hostname list is cleared. IFS The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is ``<space><tab><newline>''. IGNOREEOF Controls the action of an interactive shell on receipt of an EOF character as the sole input. If set, the value is the number of consecutive EOF characters which must be typed as the first characters on an input line before bash exits. If the variable exists but does not have a nu‐ meric value, or has no value, the default value is 10. If it does not exist, EOF signifies the end of input to the shell. INPUTRC The filename for the readline startup file, overriding the default of ~/.inputrc (see READLINE below). INSIDE_EMACS If this variable appears in the environment when the shell starts, bash assumes that it is running inside an Emacs shell buffer and may dis‐ able line editing, depending on the value of TERM. LANG Used to determine the locale category for any category not specifically selected with a variable starting with LC_. LC_ALL This variable overrides the value of LANG and any other LC_ variable specifying a locale category. LC_COLLATE This variable determines the collation order used when sorting the results of pathname expansion, and determines the behavior of range expres‐ sions, equivalence classes, and collating sequences within pathname expansion and pattern matching. LC_CTYPE This variable determines the interpretation of characters and the behavior of character classes within pathname expansion and pattern match‐ ing. LC_MESSAGES
This variable determines the locale used to translate double-quoted strings preceded by a $. LC_NUMERIC This variable determines the locale category used for number formatting. LC_TIME This variable determines the locale category used for data and time formatting. LINES Used by the select compound command to determine the column length for printing selection lists. Automatically set if the checkwinsize option is enabled or in an interactive shell upon receipt of a SIGWINCH. MAIL If this parameter is set to a file or directory name and the MAILPATH variable is not set, bash informs the user of the arrival of mail in the specified file or Maildir-format directory. MAILCHECK Specifies how often (in seconds) bash checks for mail. The default is 60 seconds. When it is time to check for mail, the shell does so be‐ fore displaying the primary prompt. If this variable is unset, or set to a value that is not a number greater than or equal to zero, the shell disables mail checking. MAILPATH A colon-separated list of filenames to be checked for mail. The message to be printed when mail arrives in a particular file may be specified by separating the filename from the message with a `?'. When used in the text of the message, $_ expands to the name of the current mailfile. Example: MAILPATH='/var/mail/bfox?"You have mail":~/shell-mail?"$_ has mail!"' Bash can be configured to supply a default value for this variable (there is no value by default), but the location of the user mail files that it uses is system dependent (e.g., /var/mail/$USER). OPTERR If set to the value 1, bash displays error messages generated by the getopts builtin command (see SHELL BUILTIN COMMANDS below). OPTERR is
initialized to 1 each time the shell is invoked or a shell script is executed. PATH The search path for commands. It is a colon-separated list of directories in which the shell looks for commands (see COMMAND EXECUTION be‐ low). A zero-length (null) directory name in the value of PATH indicates the current directory. A null directory name may appear as two ad‐ jacent colons, or as an initial or trailing colon. The default path is system-dependent, and is set by the administrator who installs bash. A common value is ``/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin''. POSIXLY_CORRECT If this variable is in the environment when bash starts, the shell enters posix mode before reading the startup files, as if the –posix invo‐ cation option had been supplied. If it is set while the shell is running, bash enables posix mode, as if the command set -o posix had been executed. When the shell enters posix mode, it sets this variable if it was not already set. PROMPT_COMMAND If this variable is set, and is an array, the value of each set element is executed as a command prior to issuing each primary prompt. If this is set but not an array variable, its value is used as a command to execute instead. PROMPT_DIRTRIM If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes (see PROMPTING below). Characters removed are replaced with an ellipsis. PS0 The value of this parameter is expanded (see PROMPTING below) and displayed by interactive shells after reading a command and before the com‐ mand is executed. PS1 The value of this parameter is expanded (see PROMPTING below) and used as the primary prompt string. The default value is ``\s-\v\$ ''. PS2 The value of this parameter is expanded as with PS1 and used as the secondary prompt string. The default is ``> ''. PS3 The value of this parameter is used as the prompt for the select command (see SHELL GRAMMAR above). PS4 The value of this parameter is expanded as with PS1 and the value is printed before each command bash displays during an execution trace. The
