Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Bash (Unix shell)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Features == === List of Short Descriptions === <!-- Suggestion 3 / 8 -- 06 Jan 2025 --> {{prose|date=January 2025}} As a [[Command-line interface|command processor]], Bash can operate in two modes: an interactive and non-interactive mode. In the interactive mode a [[Terminal emulator|text window]] where users input commands to execute various tasks. The second mode, is execution of commands from files, known as [[shell script]]s, facilitating [[automation]]. In keeping with [[Unix shell]] conventions, Bash incorporates a rich set of features, including: * A [https://www.gnu.org/software/bash/manual/index.html User Manual] provided by the GNU Project, also available at <code>info bash</code>, and a technical manual available at <code>man bash</code>. * [[Function (computer programming)|Invocation]] as a... ** [[Interactivity|Interactive]] shell, ** Non-interactive shell, or ** Login shell; * A [[command-line interface]]; * [[Exit status]] codes; * [[Control flow|Control structures]] for ** [[Conditional (computer programming)|Condition testing]], *** <code>if</code>, <code>case</code>, <code>select</code>, *** logical AND (<code>&&</code>) and OR (<code>||</code>), and ** [[Iteration]]: *** <code>for</code>, <code>while</code>, <code>until</code> loops, and *** Arithmetic C-style loop: <code>for ((</code>; * Syntaxes for Boolean testing of file attributes, string and integer values, etc.: ** Traditional <code>test</code> command, ** Traditional single bracket test: <code>[</code>, ** Modern double bracket test: <code> [[ ... ]]</code>, which includes advanced features: *** Extended [[regular expression]] and extglob matching *** Lexicographic sorting with <code><</code> and <code>></code>; * [[Unix|UNIX]]-style [[Pipeline (Unix)|pipelines]]: <code>|</code>; * [[Child process|Subshells]]: <code>$( ... )</code>; * [[Signal (IPC)|Signaling]] as a means of [[inter-process communication]] using the <code>trap</code> builtin; * Asynchronous execution, i.e., [[Job (computing)|Jobs]] and [[Job control (Unix)|job control]]: ** <code>job_spec &</code> where <code>job_spec</code> can be one of: *** A full commandline: <code><command_name> <options> <operands> <arguments> &</code>, or *** A job control identifier as denoted by a leading percent symbol: <code>%1 &</code>; * A shell [[Porting|portability]] mode where command lines can be interpreted in conformance with the [[POSIX terminal interface|POSIX]] standard; * Command parsing: ** Comments are ignored: *** Bourne-style <code>#</code> hashtag comments, and *** Thompson-style <code>:</code> colon comments; ** Commands are parsed one line at a time: *** Control structures are honored, and *** Backslash <code>\</code> escapes are also honored at the ends of lines; ** Split into words (i.e., [[Text segmentation|word splitting]]) according to [[String literal|quoting]] rules, *** Including ANSI-C quoting <code>$'...'</code>; ** Seven kinds of expansions are performed in the following order on the resulting string: *** (Step 1) Brace expansion <code>kernel{-headers}</code>, *** (Step 2) Tilde expansion <code>~</code>, *** (Step 3) In a left-to-right fashion: **** [[Parameter (computer programming)|Parameter]] and [[Variable (computer science)|variable]] expansion <code>$foo</code> or <code>${bar}</code>, including ***** [[Scope (computer science)#Dynamic scoping|Dynamically scoped]] variables, ***** Indexed [[Array (data type)|arrays]] of unlimited size, ***** [[Associative array]]s via <code>declare -A</code>, and ***** Expansion syntaxes which can perform some tasks more quickly than external utilities, including, among others: ****** Pattern Substitution ******* <code>${foo//x/y}</code> for <code>sed 's/x/y/g'</code>, ****** Remove Matching Prefix or Suffix Pattern ******* <code>${bar##[a-zA-Z0-9]*}</code> for <code>cut -c8-</code>, ****** Print Array Keys ******* <code>${!array[@]}</code>, and ****** Display Error if Null or Unset ******* <code>${var:?error message}</code>, **** [[Command substitution]]: <code>$( ... )</code>, **** [[Process substitution]], <code><()</code> or <code>>()</code>, when a system supports it: **** Arithmetic expansion, <code>(( ... ))</code> or <code>$(( ... ))</code>, including ***** Integer [[arithmetic]] in any [[Radix|base]] from two to sixty-four, although ***** [[Floating-point arithmetic]] is not available from within the shell itself (for this functionality, see current versions of [[Bc (programming language)|<code>bc</code>]] and [[AWK|<code>awk</code>]], among others), *** (Step 4) [[Text segmentation|Word splitting]] (again), *** (Step 5) Pathname expansion, i.e., shell-style [[Glob (programming)|globbing]] and [[pattern matching]] using <code>*</code>, <code>?</code>, <code>[...]</code>, and **** (Although they can be used in conjunction, the use of brackets in pattern matching, <code>[...]</code>, and the use of brackets in the testing commands, <code>[</code> and <code> [[ ... ]]</code>, are each one different things.) *** [[String literal|Quote]] removal; ** [[Redirection (computing)|Redirections]] of Standard Input, Standard Output and Standard Error [[Standard streams|data streams]] are performed, including *** File writing, <code>></code>, and appending, <code>>></code>, *** [[Here document]]s, <code><<</code>, *** Here strings, <code><<<</code>, which allow parameters to be used as input, and *** A redirection operator, <code>>|</code>, which can force overwriting of a file when a shell's "noclobber" setting is enabled; ** Command name lookup is performed, in the following order: *** [[Command (computing)|Commands]] internal to the [[Shell (computing)|shell]]: **** [[Alias (command)|Shell aliases]], **** Shell reserved words, **** [[Function (computer programming)|Shell functions]], and **** [[Shell builtin|Shell built-in commands]]; *** Commands external to the shell: **** Separate [[Unix|UNIX]]-style programs such as [[ls|<code>ls</code>]] or [[Ln (Unix)|<code>ln</code>]], and **** [[Shell script]]s, which are [[File system|files]] containing executable commands. (Shell scripts do not require compilation before execution and, when certain requirements are met, can be invoked as commands by using their filename.) ** The resulting string is executed as a command. Bash also offers... * Configurable execution environment(s):<ref>{{Cite web |title=Command Execution Environment (Bash Reference Manual) |url=https://www.gnu.org/software/bash/manual/html_node/Command-Execution-Environment.html |publisher=[[GNU Project]]}}/</ref> ** Shell and [[Session (computer science)|session]] startup files such as <code>~/.bashrc</code> and <code>~/.profile</code> (i.e., [[Hidden file and hidden directory|dotfiles]]); ** Settings (<code>set</code> [[Shell builtin|built-in]]) and shell options (<code>shopt</code> [[Shell builtin|built-in]]) which alter shell behavior; * Support for [[Unicode]]; * With interactive invocation only, ** Unlimited size [[command history]], ** A directory stack (see <code>pushd</code> and <code>popd</code> built-ins), ** [[Command-line completion|Tab completion]], ** Configurable [[Command-line interface#Command prompt|prompts]], and ** Command line editing with [[GNU Readline|GNU readline]]; * Lightweight [[Logging (computing)|logging]] for [[debugging]] purposes (xtrace), and other lightweight debugging options (errexit, noexec, nounset, pipefail, etc.); * Shell [[compatibility mode]]s: bash 5.1 can operate as if it were bash 4.2, etc.; * Various Built-In Commands: ** <code>cd</code> ** <code>pwd</code> * Documentation: ** A built-in <code>help</code> command. ** A [[man page]], and ** An [[Info (Unix)|info page]] which is the same as the GNU manual; * Informal avenues of support via: ** IRC at libera.chat #bash ** Mailing lists at [https://www.gnu.org/software/bash/ Bash] - GNU Project - Free Software Foundation ===General Discussion=== The Bash [[command (computing)|command]] syntax is a [[superset]] of the Bourne shell command syntax. Bash supports [[brace expansion]],<ref>{{Cite web |title=Brace Expansion (Bash Reference Manual) |url=https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html |archive-url=https://web.archive.org/web/20180315115230/http://www.gnu.org/software/bash/manual/bash.html#Programmable-Completion |archive-date=March 15, 2018 |access-date=2024-01-10 |publisher=[[GNU Project]] }}</ref> [[command line completion]] (Programmable Completion),<ref>{{Cite web |title=Bash Reference Manual: Programmable Completion |url=https://www.gnu.org/software/bash/manual/bash.html#Programmable-Completion |website=[[GNU Project]] }}</ref> basic debugging<ref>{{Cite web |title=Debugging Bash scripts |url=http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html |url-status=live |archive-url=https://web.archive.org/web/20181104185300/http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html |archive-date=November 4, 2018 |access-date=November 20, 2018 |website=tldp.org }}</ref><ref>{{Cite web |title=The Set Builtin (Bash Reference Manual) |url=https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html |access-date=2024-01-10 |publisher=[[GNU Project]] }}</ref> and [[Signal (IPC)|signal handling]] (using <code>trap</code>) since bash 2.05a<ref>{{Cite web |title=Bash changes [Bash Hackers Wiki (DEV 20200708T2203)] |url=https://wiki-dev.bash-hackers.org/scripting/bashchanges |url-status=live |archive-url=https://web.archive.org/web/20190923203509/https://wiki-dev.bash-hackers.org/scripting/bashchanges |archive-date=September 23, 2019 |access-date=September 23, 2019 |website=wiki-dev.bash-hackers.org }}</ref><ref>{{Cite web |title=Bourne Shell Builtins (Bash Reference Manual) |url=https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html |access-date=2024-01-10 |publisher=[[GNU Project]] }}</ref> among other features. Bash can execute the vast majority of Bourne shell scripts without modification, with the exception of Bourne shell scripts stumbling into fringe syntax behavior interpreted differently in Bash or attempting to run a system command matching a newer Bash builtin, etc. Bash command syntax includes ideas drawn from the [[KornShell|Korn Shell]] (ksh) and the [[C shell]] (csh) such as command line editing, [[command history]] (<code>history</code> command),<ref>{{Cite web |title=Bash Reference Manual |url=https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Bash-History-Builtins |url-status=live |archive-url=https://web.archive.org/web/20190915123105/http://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Bash-History-Builtins |archive-date=September 15, 2019 |access-date=September 15, 2019 |publisher=[[GNU Project]] }}</ref> the directory stack, the <code>$RANDOM</code> and <code>$PPID</code> variables, and POSIX [[command substitution]] syntax <code>$(...)</code>. When a user presses the [[tab key]] within an interactive command-shell, Bash automatically uses [[command line completion]], since beta version 2.04,<ref name="auto1">{{Cite web |title=Working more productively with bash 2.x/3.x |url=http://www.caliban.org/bash/index.shtml |url-status=live |archive-url=https://web.archive.org/web/20180629230903/http://www.caliban.org/bash/index.shtml |archive-date=June 29, 2018 |access-date=June 21, 2018 |website=caliban.org }}</ref> to match partly typed program names, filenames and variable names. The Bash command-line completion system is very flexible and customizable, and is often packaged with functions that complete arguments and filenames for specific programs and tasks. Bash's syntax has many extensions lacking in the Bourne shell. Bash can perform integer calculations ("arithmetic evaluation") without spawning external processes. It uses the <code>((...))</code> command and the <code>$((...))</code> variable syntax for this purpose. Its syntax simplifies [[redirection (computing)|I/O redirection]]. For example, it can redirect [[standard out]]put (stdout) and [[Standard error stream|standard error]] (stderr) at the same time using the <code>&></code> operator. This is simpler to type than the Bourne shell equivalent '<code>command > file 2>&1</code>'. Bash supports [[process substitution]] using the <code><(command)</code> and <code>>(command)</code>syntax, which substitutes the output of (or input to) a command where a filename is normally used. (This is implemented through ''/proc/fd/'' unnamed pipes on systems that support that, or via temporary [[named pipe]]s where necessary). When using the 'function' keyword, Bash function declarations are not compatible with Bourne/Korn/POSIX scripts (the KornShell has the same problem when using 'function'), but Bash accepts the same function declaration syntax as the Bourne and Korn shells, and is POSIX-conformant. Because of these and other differences, Bash shell scripts are rarely runnable under the Bourne or Korn shell interpreters unless deliberately written with that compatibility in mind, which is becoming less common as Linux becomes more widespread. But in POSIX mode, Bash conforms with POSIX more closely.<ref name="GNUBASHREF">{{Citation |title=The GNU Bash Reference Manual, for Bash, Version 4.1 |date=December 23, 2009 |url=https://www.gnu.org/software/bash/manual/html_node/index.html |access-date=October 26, 2010 |archive-url=https://web.archive.org/web/20101203065400/https://www.gnu.org/software/bash/manual/html_node/index.html |archive-date=December 3, 2010 |url-status=live |chapter=6.11 Bash POSIX Mode |chapter-url=https://www.gnu.org/software/bash/manual/html_node/Bash-POSIX-Mode.html }}</ref> Bash supports [[here document]]s. Since version 2.05b Bash can redirect [[Stdin|standard input]] (stdin) from a "here string" using the <code><<<</code> operator. Bash 3.0 supports in-process [[regular expression]] matching using a syntax reminiscent of [[Perl]].<ref>{{Cite web |title=Advanced Bash-Scripting Guide |url=http://www.tldp.org/LDP/abs/html/bashver3.html#BASH3REF |url-status=live |archive-url=https://web.archive.org/web/20170505161903/http://tldp.org/LDP/abs/html/bashver3.html#BASH3REF |archive-date=May 5, 2017 |access-date=2017-03-05 |website=tldp.org |at=Section 37.2 (Bash, version 3) }}</ref> In February 2009,<ref>{{Cite web |title=Bash, version 4 |url=http://tldp.org/LDP/abs/html/bashver4.html |url-status=live |archive-url=https://web.archive.org/web/20180701001653/http://www.tldp.org/LDP/abs/html/bashver4.html |archive-date=July 1, 2018 |access-date=June 25, 2018 |website=tldp.org }}</ref> Bash 4.0 introduced support for [[associative arrays]].<ref name="bashfaq061" /> Associative array indices are strings, in a manner similar to [[AWK]] or [[Tcl]].<ref>{{Cite web |title=Arrays (Bash Reference Manual) |url=https://www.gnu.org/software/bash/manual/html_node/Arrays.html |url-status=live |archive-url=https://web.archive.org/web/20180711142941/http://www.gnu.org/software/bash/manual/html_node/Arrays.html |archive-date=July 11, 2018 |access-date=July 4, 2018 |publisher=[[GNU Project]] }}</ref> They can be used to emulate multidimensional arrays. Bash 4 also switches its license to [[GNU General Public License#Version 3|GPL-3.0-or-later]].<ref>{{Cite web |title=macos - Update bash to version 4.0 on OSX |url=https://apple.stackexchange.com/questions/193411/update-bash-to-version-4-0-on-osx |url-status=live |archive-url=https://web.archive.org/web/20180625213216/https://apple.stackexchange.com/questions/193411/update-bash-to-version-4-0-on-osx |archive-date=June 25, 2018 |access-date=June 25, 2018 |website=Ask Different }}</ref> <!-- === Exit Codes === --> === Control Structures === <!-- '''+++ <code>if</code>''' '''+++ <code>case</code>''' '''+++ <code>for</code>''' '''+++ <code>for ((</code>''' '''+++ <code>while</code> and <code>until</code>''' '''+++ <code>&&</code> and <code>||</code>''' --> Bash supplies "conditional execution" command separators that make execution of a command contingent on the [[Exit status|exit code]] set by a precedent command. For example: <syntaxhighlight lang="bash"> cd "$SOMEWHERE" && ./do_something || echo "An error occurred" >&2 </syntaxhighlight> Where {{code|./do_something}} is only executed if the {{code|cd}} (change directory) command was "successful" (returned an exit status of zero) and the {{code|echo}} command would only be executed if either the {{code|cd}} or the {{code|./do_something}} command return an "error" (non-zero exit status). For all commands the exit status is stored in the special variable <code>$?</code>. Bash also supports {{code|2=bash|if ...;then ...;else ...;fi}} and {{code|2=bash|case $VARIABLE in $pattern)...;;$other_pattern)...;; esac}} forms of conditional command evaluation. <!-- === Boolean Testing === '''+++ <code>test</code> Built-In and Binary''' '''+++ Single Bracket <code>[</code> Built-In and Binary''' '''+++ Double Bracket <code>[[</code> Built-In (and no Binary)''' --><!-- === Pipelines === --><!-- === Subshells === '''+++ Standard Subshells <code>(...)</code>''' '''+++ Command Substitutions <code>$(...)</code>''' '''+++ Pipelines (again) <code>| ... |</code>''' --><!-- === Signals === --> === Process Management (a.k.a., "Job control") === The Bash shell has two modes of execution for commands: batch (asynchronous), and concurrent (synchronous). To execute commands in batch mode (i.e., in sequence) they must be separated by the character ";", or on separate lines: <syntaxhighlight lang="bash"> command1; command2 command3 </syntaxhighlight> In this example, when command1 is finished, command2 is executed, and when command2 has completed, command3 will execute. A [[Background process|background execution]] of command1 can occur using (symbol &) at the end of an execution command, and process will be executed in background while immediately returning control to the shell and allowing continued execution of commands. <syntaxhighlight lang="bash">command1 &</syntaxhighlight> Or to have a concurrent execution of command1 and command2, they must be executed in the Bash shell in the following way: <syntaxhighlight lang="bash"> command1 & command2 </syntaxhighlight> In this case command1 is executed in the background ''&'' symbol, returning immediately control to the shell that executes command2 in the foreground. A process can be stopped and control returned to bash by typing {{Key press|Ctrl|z}} while the process is running in the foreground.<ref>{{Cite web |title=Bash Reference Manual |url=https://www.gnu.org/software/bash/manual/bash.html#index-background |url-status=live |archive-url=https://web.archive.org/web/20180315115230/http://www.gnu.org/software/bash/manual/bash.html#index-background |archive-date=March 15, 2018 |access-date=March 27, 2018 |publisher=[[GNU Project]] }}</ref> A list of all processes, both in the background and stopped, can be achieved by running <code>jobs</code>: <syntaxhighlight lang="console"> $ jobs [1]- Running command1 & [2]+ Stopped command2 </syntaxhighlight> In the output, the number in brackets refers to the job id. The plus sign signifies the default process for <code>bg</code> and <code>fg</code>. The text "Running" and "Stopped" refer to the [[process state]]. The last string is the command that started the process. The state of a process can be changed using various commands. The <code>fg</code> command brings a process to the foreground, while <code>bg</code> sets a stopped process running in the background. <code>bg</code> and <code>fg</code> can take a job id as their first argument, to specify the process to act on. Without one, they use the default process, identified by a plus sign in the output of <code>jobs</code>. The <code>[[Kill (command)|kill]]</code> command can be used to end a process prematurely, by sending it a [[Signal (IPC)|signal]]. The job id must be specified after a percent sign: <syntaxhighlight lang="bash"> kill %1 </syntaxhighlight> === Portability with POSIX === Invoking Bash with the <code>--posix</code> option or stating <code>set -o posix</code> in a script causes Bash to conform very closely with the [[Posix#POSIX.2|POSIX 1003.2 standard]].<ref name="tldp">{{Cite web |last=Mendel Cooper |title=Portability Issues |url=http://tldp.org/LDP/abs/html/portabilityissues.html |url-status=live |archive-url=https://web.archive.org/web/20120127105451/http://tldp.org/LDP/abs/html/portabilityissues.html |archive-date=January 27, 2012 |access-date=January 26, 2012 |website=The Linux Documentation Project |publisher=ibiblio.org }}</ref> Bash shell scripts intended for [[portability (computer science)|portability]] should take into account at least the POSIX shell standard. Some bash features not found in POSIX are:<ref name="tldp" /><ref name="deb">{{Cite web |title=10. Files |url=https://www.debian.org/doc/debian-policy/ch-files.html#scripts |url-status=live |archive-url=https://web.archive.org/web/20200512050159/https://www.debian.org/doc/debian-policy/ch-files.html#scripts |archive-date=May 12, 2020 |access-date=May 11, 2020 |website=Debian Policy Manual v4.5.0.2 }}</ref> {{div col start}} * Certain extended invocation options * Brace expansion * Arrays and associative arrays * The double bracket {{code| [[...]] }} extended test construct and its regex matching * The double-parentheses arithmetic-evaluation construct (only {{code|(( ... ))}}; {{code|$(( ... ))}} is POSIX) * Certain string-manipulation operations in parameter expansion * {{code|local}} for scoped variables * Process substitution * Bash-specific builtins * [[Coprocess]]es * $EPOCHSECONDS and $EPOCHREALTIME variables<ref>{{Cite web |title=How To Format Date And Time In Linux, MacOS, And Bash? |url=https://www.shell-tips.com/linux/how-to-format-date-and-time-in-linux-macos-and-bash/#using-the-gnu-date-command-line |url-status=live |archive-url=https://web.archive.org/web/20200603230615/https://www.shell-tips.com/linux/how-to-format-date-and-time-in-linux-macos-and-bash/#using-the-gnu-date-command-line |archive-date=June 3, 2020 |access-date=June 3, 2020 |website=Shell Tips! }}</ref> {{div col end}} If a piece of code uses such a feature, it is called a "bashism" β a problem for portable use. Debian's {{code|checkbashisms}} and Vidar Holen's {{code|shellcheck}} can be used to make sure that a script does not contain these parts.<ref name="checkbashisms, ManKier man page">{{man|1|checkbashisms|ManKier}}</ref><ref name="shellcheck, ManKier man page">{{man|1|shellcheck|ManKier}}</ref> The list varies depending on the actual target shell: Debian's policy allows some extensions in their scripts (as they are in the [[Almquist shell#Dash|dash]] shell),<ref name=deb/> while a script intending to support pre-POSIX Bourne shells, like [[autoconf]]'s {{code|configure}}, are even more limited in the features they can use.<ref>{{Cite web |title=Portable Shell |url=https://www.gnu.org/software/autoconf/manual/html_node/Portable-Shell.html |url-status=live |archive-url=https://web.archive.org/web/20210302212413/https://www.gnu.org/savannah-checkouts/gnu/autoconf/manual/autoconf-2.70/html_node/Portable-Shell.html |archive-date=March 2, 2021 |access-date=20 January 2020 |website=Autoconf }}</ref> <!-- === Comments === === Word Splitting & Quoting === '''+++ Backslash <code>\</code>''' '''+++ Double Quotes <code>"..."</code>''' '''+++ Single Quotes <code>'...'</code>''' '''+++ ANSI-C Quoting <code>$'...'</code>''' --> === Brace Expansion === Brace expansion, also called alternation, is a feature copied from the [[C shell]]. It generates a set of alternative combinations. Generated results need not exist as files. The results of each expanded string are not sorted and left to right order is preserved: <syntaxhighlight lang="console"> $ echo a{p,c,d,b}e ape ace ade abe $ echo {a,b,c}{d,e,f} ad ae af bd be bf cd ce cf </syntaxhighlight> Users should not use brace expansions in portable shell scripts, because the [[Bourne shell]] does not produce the same output. <syntaxhighlight lang="console"> $ # bash shell $/bin/bash -c 'echo a{p,c,d,b}e' ape ace ade abe $ # A traditional shell does not produce the same output $ /bin/sh -c 'echo a{p,c,d,b}e' a{p,c,d,b}e </syntaxhighlight> When brace expansion is combined with wildcards, the braces are expanded first, and then the resulting wildcards are substituted normally. Hence, a listing of JPEG and PNG images in the current directory could be obtained using: <syntaxhighlight lang="bash"> ls *.{jpg,jpeg,png} # expands to *.jpg *.jpeg *.png β after which, # the wildcards are processed echo *.{png,jp{e,}g} # echo just shows the expansions β # and braces in braces are possible. </syntaxhighlight> In addition to alternation, brace expansion can be used for sequential ranges between two integers or characters separated by double dots. Newer versions of Bash allow a third integer to specify the increment. <syntaxhighlight lang="console"> $ echo {1..10} 1 2 3 4 5 6 7 8 9 10 $ echo {01..10} 01 02 03 04 05 06 07 08 09 10 $ echo file{1..4}.txt file1.txt file2.txt file3.txt file4.txt $ echo {a..e} a b c d e $ echo {1..10..3} 1 4 7 10 $ echo {a..j..3} a d g j </syntaxhighlight> When brace expansion is combined with variable expansion (A.K.A. ''parameter expansion'' and ''parameter substitution'') the variable expansion is performed ''after'' the brace expansion, which in some cases may necessitate the use of the <code>eval</code> built-in, thus: <syntaxhighlight lang="console"> $ start=1; end=10 $ echo {$start..$end} # fails to expand due to the evaluation order {1..10} $ eval echo {$start..$end} # variable expansion occurs then resulting string is evaluated 1 2 3 4 5 6 7 8 9 10 </syntaxhighlight> <!-- === Tilde Expansion === --><!-- === Parameter and Variable Expansion === '''+++ Attributes''' '''+++ Scalar Variables''' '''+++ Array Variables''' '''++++++ Indexed Arrays''' '''++++++ Associative Arrays''' '''+++ Shell Variables''' '''++++++ Positional Parameters''' '''++++++ Special Variables''' '''++++++ POSIX Variables''' '''++++++ Non-POSIX Variables''' '''+++ <code>export</code> and Environment Variables''' --><!-- === Command Substitution (again) === '''+++ Modern <code>$(...)</code>''' '''+++ Deprecated <code>`...`</code>''' --><!-- === Process Substitution (again) === '''+++ <code><(...)</code> and <code>>(...)</code>''' --><!-- === Arithmetic Expansion === '''+++ <code>((..))</code>''' '''+++ <code>$((...))</code>''' '''+++ Other Arithmetic Contexts''' '''+++ Integer Variables''' --><!-- === Redirections === '''+++ Standard''' '''+++ Here Documents''' '''+++ Here Strings''' --><!-- === Aliases === --><!-- === Reserved Words and Grammar === --><!-- === Functions === --><!-- === Built-Ins === --><!-- === Command Lookup === --> === Configurable execution environment(s) === ==== Shell and Session Startup Files (a.k.a., "Dot Files") ==== <!-- Suggestion 4 / 8 -- 06 Jan 2025 --> {{ How-to section | date=January 2019 }} When Bash starts, it executes the commands in a variety of [[Hidden file and hidden directory#Unix and Unix-like environments|dot files]].<ref>{{Cite web |title=I Almost Get a Linux Editor and Compiler |url=http://www.drdobbs.com/i-almost-get-a-linux-editor-and-compiler/184404693 |url-status=live |archive-url=https://web.archive.org/web/20210302212410/https://www.drdobbs.com/i-almost-get-a-linux-editor-and-compiler/184404693 |archive-date=March 2, 2021 |access-date=2020-09-12 |website=Dr. Dobb's |quote=But virtually all the configure and install scripts that come with open-source programs are written for bash, and if you want to understand those scripts, you have to know bash. }}</ref> Unlike Bash shell scripts, dot files do typically have neither the execute permission enabled nor an [[interpreter directive]] like <code>#!/bin/bash</code>. ===== Legacy-compatible Bash startup example ===== The example <code>~/.bash_profile</code> below is compatible with the Bourne shell and gives semantics similar to csh for the <code>~/.bashrc</code> and <code>~/.bash_login</code>. The <code>[ -r ''filename'' ] && cmd</code> is a [[short-circuit evaluation]] that tests if ''filename'' exists and is readable, skipping the part after the <code>&&</code> if it is not. <syntaxhighlight lang="bash"> [ -r ~/.profile ] &&. ~/.profile # set up environment, once, Bourne-sh syntax only if [ -n "$PS1" ]; then # are we interactive? [ -r ~/.bashrc ] &&. ~/.bashrc # tty/prompt/function setup for interactive shells [ -r ~/.bash_login ] &&. ~/.bash_login # any at-login tasks for login shell only fi # End of "if" block </syntaxhighlight> ===== Operating system issues in Bash startup ===== Some versions of [[Unix]] and [[Linux]] contain Bash system startup scripts, generally under the <code>/etc</code> directory. Bash executes these files as part of its standard initialization, but other startup files can read them in a different order than the documented Bash startup sequence. The default content of the root user's files may also have issues, as well as the skeleton files the system provides to new user accounts upon setup. The startup scripts that launch the [[X window system]] may also do surprising things with the user's Bash startup scripts in an attempt to set up user-environment variables before launching the [[window manager]]. These issues can often be addressed using a <code>~/.xsession</code> or <code>~/.xprofile</code> file to read the <code>~/.profile</code> β which provides the environment variables that Bash shell windows spawned from the window manager need, such as [[xterm]] or [[Gnome Terminal]]. ==== Settings and Shell Options ==== ===== The <code>set</code> Built-in ===== * Xtrace: [ <code>set -x</code> | <code>set -o xtrace</code> ] The shell's primary means of debugging. Both xtrace and verbose can be turned off at the same time with the command <code>set -</code>. * Verbose: [ <code>set -v</code> | <code>set -o verbose</code> ] Prints a command to the terminal as Bash reads it. Bash reads constructs all at once, such as compound commands which include if-fi and case-esac blocks. If a <code>set -v</code> is included within a compound command, then "verbose" will be enabled the next time Bash reads code as input, i.e., after the end of the currently executing construct.<ref>{{Cite mailing list |mailing-list=bug-bash |date=20 April 2021 |title=bug-bash archives, Re: Document that set -v inside case statements is special |url=https://lists.gnu.org/archive/html/bug-bash/2021-04/msg00172.html }}</ref> Both xtrace and verbose can be turned off at the same time with the command <code>set -</code>. ===== The <code>shopt</code> Built-in ===== * expand-aliases On by default in interactive shells. Some developers discourage its use in scripts. <!-- === Localization === '''+++ Environment Variables beginning with <code>LC_*</code> ''' '''+++ Locale-specific Expansion <code>$"..."</code>''' --><!-- === Reporting the Time === '''+++ <code>SECONDS</code>, <code>EPOCHSECONDS</code> and <code>EPOCHREALTIME</code>''' '''+++ The <code>printf</code> Builtin (and not the Binary)''' '''+++ The <code>date</code> Binary and <code>LC_TIME</code>''' --><!-- === Command History === --><!-- === Tab Completion === --> === Programmable Completion === Bash supports programmable [[Command-line completion|completion]] via built-in <code>complete</code>, {{Code|compopt}}, and <code>compgen</code> commands.<ref>{{Cite web |title=Bash Reference Manual |url=https://tiswww.case.edu/php/chet/bash/bashref.html#Programmable-Completion |website=tiswww.case.edu }}</ref> The feature has been available since the beta version of 2.04 released in 2000.<ref name="auto1"/><ref>{{Cite web |title=Index of /gnu/bash |url=https://ftp.swin.edu.au/gnu/bash/ |url-status=live |archive-url=https://web.archive.org/web/20200308104032/http://ftp.swin.edu.au/gnu/bash/ |archive-date=March 8, 2020 |access-date=September 15, 2019 |website=ftp.swin.edu.au }}</ref> These commands enable complex and intelligent completion specification for commands (i.e. installed programs), functions, variables, and filenames.<ref name=":1">{{Cite web |title=An Introduction to Programmable Completion |url=https://tldp.org/LDP/abs/html/tabexpansion.html |access-date=2022-01-21 |website=tldp.org }}</ref> The <code>complete</code> and {{Code|compopt}} two commands specify how arguments of some available commands or options are going to be listed in the [[readline]] input. As of version 5.1 completion of the command or the option is usually activated by the {{Key|tab}} keystroke after typing its name.<ref name=":1" /> <!-- === Shell-native Pattern Matching === '''+++ Wildcards (a.k.a., "Globs"): <code>*</code> <code>[...]</code> and <code>?</code>''' '''+++ Pattern Matching Contexts''' --><!-- === Regular Expressions === '''+++ The Regex Operator (<code>=~</code>) of the Double Bracket Keyword (<code>[[</code>)''' '''+++ <code>BASH_REMATCH</code>''' --><!-- === Coprocesses === --> === Keyboard shortcuts with Readline === {{ Main | GNU Readline }} Bash uses [[GNU Readline]] to provide keyboard shortcuts for command line editing using the default ([[Emacs]]) key bindings. [[Vi-binding]]s can be enabled by running <code>set -o vi</code>.<ref>{{Cite web |date=October 5, 2012 |title=BASH Help - A Bash Tutorial |url=http://www.hypexr.org/bash_tutorial.php#emacs |url-status=live |archive-url=https://web.archive.org/web/20210302213519/http://www.hypexr.org/bash_tutorial.php#emacs |archive-date=March 2, 2021 |access-date=July 21, 2013 |publisher=Hypexr.org }}</ref> <!-- === Observability === '''+++ <code>set</code> and <code>env</code>''' '''+++ <code>getconf</code>''' '''+++ <code>compgen</code>''' '''+++ Exit Codes (again?)''' '''+++ Xtrace and Verbose Modes''' --><!-- === Programming Paradigm === -->
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)