Fix hyperlinks of markdown pages at depth 2

find docs/ -depth 2  -name '*.md' | xargs grep '(.*/' -l | \
  xargs -I{} \
  sed -i '' \
  -e 's%(/\([^/#).][^/#).]*\)/\([^/#).][^/#).]*\)\(.md\)\{0\})%(../\1/\2.md)%g' \
  -e 's%(/\([^/#).][^/#).]*\)/\([^/#).][^/#).]*\)#\([0-9a-zA-Z_-][0-9a-zA-Z_-]*\))%(../\1/\2.md#\3)%g' \
  -e 's%(/\([^/#).][^/#).]*\)/\([^/#).][^/#).]*\)/\([^/#).][^/#).]*\)\(.md\)\{0\})%(../\1/\2/\3.md)%g' \
  -e 's%(/\([^/#).][^/#).]*\)/\([^/#).][^/#).]*\)/\([^/#).][^/#).]*\)#\([0-9a-zA-Z_-][0-9a-zA-Z_-]*\))%(../\1/\2/\3.md#\4)%g' \
  -e 's%](\([^:.>)#][^:.>)#]*\))%](../\1.md)%g' \
  -e 's%](\([^:.>)#][^:.>)#]*\)#\([^:.>)#][^:.>)#]*\))%](../\1.md#\2)%g' \
  {}

Related to https://github.com/flokoe/bash-hackers-wiki/issues/10
This commit is contained in:
Hanson Char 2024-01-28 17:01:50 -08:00
parent 92be6d2c2c
commit e966036f05
39 changed files with 358 additions and 358 deletions

View File

@ -61,7 +61,7 @@ fi
As you definitely noted, the filename contains spaces. As you definitely noted, the filename contains spaces.
Since we call a normal ordinary command (`test` or `[`) the shell will word-split the expansion of the variable `mymusic`: Since we call a normal ordinary command (`test` or `[`) the shell will word-split the expansion of the variable `mymusic`:
You need to quote it when you don't want the `test`-command to complain about too many arguments for this test-type! You need to quote it when you don't want the `test`-command to complain about too many arguments for this test-type!
If you didn't understand it, please read the [article about words\...](/syntax/words). If you didn't understand it, please read the [article about words\...](../syntax/words.md).
Please also note that the file-tests want **one filename** to test. Please also note that the file-tests want **one filename** to test.
Don't give a glob (filename-wildcards) as it can expand to many filenames => **too many arguments!** Don't give a glob (filename-wildcards) as it can expand to many filenames => **too many arguments!**
@ -138,7 +138,7 @@ Since Bash 4.1, all tests related to permissions respect ACLs, if the underlying
| <TEST1\> **-o** <TEST2\> | True, if either \<TEST1\> **or** <TEST2\> is true (OR). | | <TEST1\> **-o** <TEST2\> | True, if either \<TEST1\> **or** <TEST2\> is true (OR). |
| **!** <TEST\> | True, if <TEST\> is **false** (NOT). | | **!** <TEST\> | True, if <TEST\> is **false** (NOT). |
| **(** <TEST\> **)** | Group a test (for precedence). **Attention:** In normal shell-usage, the `(` and `)` must be escaped; use `\(` and `\)`! | | **(** <TEST\> **)** | Group a test (for precedence). **Attention:** In normal shell-usage, the `(` and `)` must be escaped; use `\(` and `\)`! |
| **-o** <OPTION_NAME\> | True, if the [shell option](/internals/shell_options) <OPTION_NAME\> is set. | | **-o** <OPTION_NAME\> | True, if the [shell option](../internals/shell_options.md) <OPTION_NAME\> is set. |
| **-v** <VARIABLENAME\> | True if the variable <VARIABLENAME\> has been set. Use `var[n]` for array elements. | | **-v** <VARIABLENAME\> | True if the variable <VARIABLENAME\> has been set. Use `var[n]` for array elements. |
| **-R** <VARIABLENAME\> | True if the variable <VARIABLENAME\> has been set and is a nameref variable (since 4.3-alpha) | | **-R** <VARIABLENAME\> | True if the variable <VARIABLENAME\> has been set and is a nameref variable (since 4.3-alpha) |
@ -503,18 +503,18 @@ Some code snipplets follow, different ways of shell reaction is used.
- **check if a variable is defined/non-NULL** - **check if a variable is defined/non-NULL**
- `test "$MYVAR"` - `test "$MYVAR"`
- `[ "$MYVAR" ]` - `[ "$MYVAR" ]`
- **Note:** There are possibilities to make a difference if a variable is *undefined* or *NULL* - see [Parameter Expansion - Using an alternate value](/syntax/pe#use_an_alternate_value) - **Note:** There are possibilities to make a difference if a variable is *undefined* or *NULL* - see [Parameter Expansion - Using an alternate value](../syntax/pe.md#use_an_alternate_value)
- **check if a directory exists, if not, create it** - **check if a directory exists, if not, create it**
- `test ! -d /home/user/foo && mkdir /home/user/foo` - `test ! -d /home/user/foo && mkdir /home/user/foo`
- `[ ! -d /home/user/foo ] && mkdir /home/user/foo` - `[ ! -d /home/user/foo ] && mkdir /home/user/foo`
- `if [ ! -d /home/user/foo ]; then mkdir /home/user/foo; fi` - `if [ ! -d /home/user/foo ]; then mkdir /home/user/foo; fi`
- **check if minimum one parameter was given, and that one is "Hello"** - **check if minimum one parameter was given, and that one is "Hello"**
- `test $# -ge 1 -a "$1" = "Hello" || exit 1` - `test $# -ge 1 -a "$1" = "Hello" || exit 1`
- `[ $# -ge 1 ] && [ "$1" = "Hello" ] || exit 1` (see [lists description](/syntax/basicgrammar#lists)) - `[ $# -ge 1 ] && [ "$1" = "Hello" ] || exit 1` (see [lists description](../syntax/basicgrammar.md#lists))
### Listing directories ### Listing directories
Using a [for-loop](/syntax/ccmd/classic_for) to iterate through all entries of a directory, if an entry is a directory (`[ -d "$fn" ]`), print its name: Using a [for-loop](../syntax/ccmd/classic_for.md) to iterate through all entries of a directory, if an entry is a directory (`[ -d "$fn" ]`), print its name:
```bash ```bash
for fn in *; do for fn in *; do
@ -524,8 +524,8 @@ done
## See also ## See also
- Internal: [conditional expression](/syntax/ccmd/conditional_expression) (aka "the new test command") - Internal: [conditional expression](../syntax/ccmd/conditional_expression.md) (aka "the new test command")
- Internal: [the if-clause](/syntax/ccmd/if_clause) - Internal: [the if-clause](../syntax/ccmd/if_clause.md)
[^1]: <rant\>Of course, one can wonder what is the use of including the [^1]: <rant\>Of course, one can wonder what is the use of including the
parenthesis in the specification without defining the behaviour with parenthesis in the specification without defining the behaviour with

View File

@ -1,7 +1,7 @@
# Directory # Directory
In terms of UNIX(r), a directory is a special file which contains a list In terms of UNIX(r), a directory is a special file which contains a list
of [hardlinks](/dict/terms/hardlink) to other files. These other files of [hardlinks](../dict/terms/hardlink.md) to other files. These other files
also can be directories of course, so it\'s possible to create a also can be directories of course, so it\'s possible to create a
\"hierarchy of directories\" - the UNIX(r)-typical filesystem structure. \"hierarchy of directories\" - the UNIX(r)-typical filesystem structure.
@ -10,6 +10,6 @@ all other directory entries are **subdirectories** of it.
## See also ## See also
- [hardlink](/dict/terms/hardlink) - [hardlink](../dict/terms/hardlink.md)
- [file](/dict/terms/file) - [file](../dict/terms/file.md)
- [special file](/dict/terms/special_file) - [special file](../dict/terms/special_file.md)

View File

@ -28,4 +28,4 @@ except
## See also ## See also
- Scripting article, internal: - Scripting article, internal:
[getopts_tutorial](/howto/getopts_tutorial) [getopts_tutorial](../howto/getopts_tutorial.md)

View File

@ -1,8 +1,8 @@
# File # File
A file is a pool of data in the [filesystem](/dict/terms/filesystem). On A file is a pool of data in the [filesystem](../dict/terms/filesystem.md). On
userlevel, it\'s referenced using a name, a userlevel, it\'s referenced using a name, a
[hardlink](/dict/terms/hardlink) to the file. [hardlink](../dict/terms/hardlink.md) to the file.
If a file is not referenced anymore (number of hardlinks to it drops to If a file is not referenced anymore (number of hardlinks to it drops to
0) then the space allocated for that file is re-used, unless it\'s still 0) then the space allocated for that file is re-used, unless it\'s still
@ -10,15 +10,15 @@ used by some process.
The file-data splits into actual payload (file contents) and some The file-data splits into actual payload (file contents) and some
metadata like filesize, filemode or timestamps. The metadata is stored metadata like filesize, filemode or timestamps. The metadata is stored
in the [inode](/dict/terms/inode). in the [inode](../dict/terms/inode.md).
Strictly spoken, a [hardlink](/dict/terms/hardlink) (also called Strictly spoken, a [hardlink](../dict/terms/hardlink.md) (also called
\"filename\") points to the [inode](/dict/terms/inode) which organizes a \"filename\") points to the [inode](../dict/terms/inode.md) which organizes a
file, not to the file itself. file, not to the file itself.
## See also ## See also
- [filesystem](/dict/terms/filesystem) - [filesystem](../dict/terms/filesystem.md)
- [filetimes](/dict/terms/filetimes) - [filetimes](../dict/terms/filetimes.md)
- [hardlink](/dict/terms/hardlink) - [hardlink](../dict/terms/hardlink.md)
- [inode](/dict/terms/inode) - [inode](../dict/terms/inode.md)

View File

@ -23,9 +23,9 @@ which serves the same purpose.
## See also ## See also
- [shell](/dict/terms/shell) - [shell](../dict/terms/shell.md)
- [hardlink](/dict/terms/hardlink) - [hardlink](../dict/terms/hardlink.md)
## See also (article) ## See also (article)
- [pathname expansion](/syntax/expansion/globs) - [pathname expansion](../syntax/expansion/globs.md)

View File

@ -4,16 +4,16 @@ Also the article for:
- filename - filename
A hardlink associates a *filename* with a [file](/dict/terms/file). That A hardlink associates a *filename* with a [file](../dict/terms/file.md). That
name is an entry in a directory listing. Of course a file can have more name is an entry in a directory listing. Of course a file can have more
hardlinks to it (usually the number of hardlinks to a file is limited), hardlinks to it (usually the number of hardlinks to a file is limited),
but all hardlinks to a file must reside on the same but all hardlinks to a file must reside on the same
[filesystem](/dict/terms/filesystem) as the file itself! [filesystem](../dict/terms/filesystem.md) as the file itself!
What you usually call a file is just a name for that file, and thus, a What you usually call a file is just a name for that file, and thus, a
hardlink. hardlink.
The difference between a [symbolic link](/dict/terms/symlink) and a hard The difference between a [symbolic link](../dict/terms/symlink.md) and a hard
link is that there is no easy way to differentiate between a \'real\' link is that there is no easy way to differentiate between a \'real\'
file and a hard link, let\'s take a look at the example: file and a hard link, let\'s take a look at the example:
@ -46,6 +46,6 @@ is freed when the last hard link pointing to it is deleted.
## See also ## See also
- [file](/dict/terms/file) - [file](../dict/terms/file.md)
- [filesystem](/dict/terms/filesystem) - [filesystem](../dict/terms/filesystem.md)
- [symlink](/dict/terms/symlink) - [symlink](../dict/terms/symlink.md)

View File

@ -40,7 +40,7 @@ A positional parameter is denoted by a number other than `0` (zero).
Positional parameters reflect the shell\'s arguments that are not given Positional parameters reflect the shell\'s arguments that are not given
to the shell itself (in practise, the script arguments, also the to the shell itself (in practise, the script arguments, also the
function arguments). You can\'t directly assign to the positional function arguments). You can\'t directly assign to the positional
parameters, however, [the set builtin command](/commands/builtin/set) parameters, however, [the set builtin command](../commands/builtin/set.md)
can be used to indirectly set them. can be used to indirectly set them.
The first to ninth positional parameter is referenced by `$1` to `$9`. The first to ninth positional parameter is referenced by `$1` to `$9`.
@ -50,7 +50,7 @@ by the number given in curly braces, i.e., `${10}` or `${432}`.
Unlike popular belief, `$0` is *not a positional parameter*. Unlike popular belief, `$0` is *not a positional parameter*.
See also the [scripting article about handling positional See also the [scripting article about handling positional
parameters](/scripting/posparams). parameters](../scripting/posparams.md).
## special parameters ## special parameters
@ -58,10 +58,10 @@ There are a bunch of special parameters, which are set by the shell.
Direct assignment to them is not possible. These parameter names are Direct assignment to them is not possible. These parameter names are
formed of one character. formed of one character.
Please see [shellvars](/syntax/shellvars). Please see [shellvars](../syntax/shellvars.md).
## See also ## See also
- Syntax article, internal: [pe](/syntax/pe) - Syntax article, internal: [pe](../syntax/pe.md)
- Syntax article, internal: [shellvars](/syntax/shellvars) - Syntax article, internal: [shellvars](../syntax/shellvars.md)
- Scripting article, internal: [posparams](/scripting/posparams) - Scripting article, internal: [posparams](../scripting/posparams.md)

View File

@ -13,4 +13,4 @@ behaviour of the system shell and some utilities (commands).
## See also ## See also
- Dictionary, internal: [shell](/dict/terms/shell) - Dictionary, internal: [shell](../dict/terms/shell.md)

View File

@ -14,6 +14,6 @@ too.
## See also ## See also
- [file](/dict/terms/file) - [file](../dict/terms/file.md)
- [filename](/dict/terms/hardlink) - [filename](../dict/terms/hardlink.md)
- [directory](/dict/terms/directory) - [directory](../dict/terms/directory.md)

View File

@ -10,6 +10,6 @@ it can
## See also ## See also
- [hardlink](/dict/terms/hardlink) - [hardlink](../dict/terms/hardlink.md)
- [filesystem](/dict/terms/filesystem) - [filesystem](../dict/terms/filesystem.md)
- [directory](/dict/terms/directory) - [directory](../dict/terms/directory.md)

View File

@ -32,13 +32,13 @@ In fact, there is a POSIX(r)-compliant command to do this: `basename`
The implementation here is suboptimal in several ways, but the only The implementation here is suboptimal in several ways, but the only
thing that\'s genuinely error-prone with this is \"`echo $i`\". Echoing thing that\'s genuinely error-prone with this is \"`echo $i`\". Echoing
an *unquoted* variable means an *unquoted* variable means
[wordsplitting](/syntax/expansion/wordsplit) will take place, so any [wordsplitting](../syntax/expansion/wordsplit.md) will take place, so any
whitespace in `$i` will essentially be normalized. In `sh` it is whitespace in `$i` will essentially be normalized. In `sh` it is
necessary to use an external command and a subshell to achieve the goal, necessary to use an external command and a subshell to achieve the goal,
but we can eliminate the pipe (subshells, external commands, and pipes but we can eliminate the pipe (subshells, external commands, and pipes
carry extra overhead when they launch, so they can really hurt carry extra overhead when they launch, so they can really hurt
performance in a loop). Just for good measure, let\'s use the more performance in a loop). Just for good measure, let\'s use the more
readable, [modern](/syntax/expansion/cmdsubst) `$()` construct instead readable, [modern](../syntax/expansion/cmdsubst.md) `$()` construct instead
of the old style backticks: of the old style backticks:
``` bash ``` bash
@ -47,7 +47,7 @@ sh $ for i in *.zip; do j=$(basename "$i" ".zip"); mkdir $j; cd $j; unzip ../$i;
In Bash we don\'t need the subshell or the external basename command. In Bash we don\'t need the subshell or the external basename command.
See [Substring removal with parameter See [Substring removal with parameter
expansion](/syntax/pe#substring_removal): expansion](../syntax/pe.md#substring_removal):
``` bash ``` bash
bash $ for i in *.zip; do j="${i%.zip}"; mkdir $j; cd $j; unzip ../$i; cd ..; done bash $ for i in *.zip; do j="${i%.zip}"; mkdir $j; cd $j; unzip ../$i; cd ..; done
@ -65,7 +65,7 @@ hurt: When a following command depends on the success of a previous
command(s), check for success! You can do this with the \"`&&`\" command(s), check for success! You can do this with the \"`&&`\"
conjunction, that way, if the previous command fails, bash will not try conjunction, that way, if the previous command fails, bash will not try
to execute the following command(s). It\'s fully POSIX(r). Oh, and to execute the following command(s). It\'s fully POSIX(r). Oh, and
remember what I said about [wordsplitting](/syntax/expansion/wordsplit) remember what I said about [wordsplitting](../syntax/expansion/wordsplit.md)
in the previous step? Well, if you don\'t quote `$j`, wordsplitting can in the previous step? Well, if you don\'t quote `$j`, wordsplitting can
happen again. happen again.

View File

@ -23,7 +23,7 @@ are:
Some other methods to parse positional parameters - using neither Some other methods to parse positional parameters - using neither
**getopt** nor **getopts** - are described in: [How to handle positional **getopt** nor **getopts** - are described in: [How to handle positional
parameters](/scripting/posparams). parameters](../scripting/posparams.md).
### Terminology ### Terminology
@ -82,15 +82,15 @@ left to parse, it\'s easy to use in a while-loop:
parsing on the first non-option argument (a string that doesn\'t begin parsing on the first non-option argument (a string that doesn\'t begin
with a hyphen (`-`) that isn\'t an argument for any option in front of with a hyphen (`-`) that isn\'t an argument for any option in front of
it). It will also stop parsing when it sees the `--` (double-hyphen), it). It will also stop parsing when it sees the `--` (double-hyphen),
which means [end of options](/dict/terms/end_of_options). which means [end of options](../dict/terms/end_of_options.md).
### Used variables ### Used variables
variable description variable description
------------------------------------ --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------ ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
[OPTIND](/syntax/shellvars#OPTIND) Holds the index to the next argument to be processed. This is how `getopts` \"remembers\" its own status between invocations. Also useful to shift the positional parameters after processing with `getopts`. `OPTIND` is initially set to 1, and **needs to be re-set to 1 if you want to parse anything again with getopts** [OPTIND](../syntax/shellvars.md#OPTIND) Holds the index to the next argument to be processed. This is how `getopts` \"remembers\" its own status between invocations. Also useful to shift the positional parameters after processing with `getopts`. `OPTIND` is initially set to 1, and **needs to be re-set to 1 if you want to parse anything again with getopts**
[OPTARG](/syntax/shellvars#OPTARG) This variable is set to any argument for an option found by `getopts`. It also contains the option flag of an unknown option. [OPTARG](../syntax/shellvars.md#OPTARG) This variable is set to any argument for an option found by `getopts`. It also contains the option flag of an unknown option.
[OPTERR](/syntax/shellvars#OPTERR) (Values 0 or 1) Indicates if Bash should display error messages generated by the `getopts` builtin. The value is initialized to **1** on every shell startup - so be sure to always set it to **0** if you don\'t want to see annoying messages! **`OPTERR` is not specified by POSIX for the `getopts` builtin utility \-\-- only for the C `getopt()` function in `unistd.h` (`opterr`).** `OPTERR` is bash-specific and not supported by shells such as ksh93, mksh, zsh, or dash. [OPTERR](../syntax/shellvars.md#OPTERR) (Values 0 or 1) Indicates if Bash should display error messages generated by the `getopts` builtin. The value is initialized to **1** on every shell startup - so be sure to always set it to **0** if you don\'t want to see annoying messages! **`OPTERR` is not specified by POSIX for the `getopts` builtin utility \-\-- only for the C `getopt()` function in `unistd.h` (`opterr`).** `OPTERR` is bash-specific and not supported by shells such as ksh93, mksh, zsh, or dash.
`getopts` also uses these variables for error reporting (they\'re set to `getopts` also uses these variables for error reporting (they\'re set to
value-combinations which arent possible in normal operation). value-combinations which arent possible in normal operation).
@ -133,7 +133,7 @@ messages.
#### Custom arguments to parse #### Custom arguments to parse
The `getopts` utility parses the [positional The `getopts` utility parses the [positional
parameters](/scripting/posparams) of the current shell or function by parameters](../scripting/posparams.md) of the current shell or function by
default (which means it parses `"$@"`). default (which means it parses `"$@"`).
You can give your own set of arguments to the utility to parse. Whenever You can give your own set of arguments to the utility to parse. Whenever
@ -346,9 +346,9 @@ Let\'s provide **the argument**:
## See also ## See also
- Internal: [posparams](/scripting/posparams) - Internal: [posparams](../scripting/posparams.md)
- Internal: [case](/syntax/ccmd/case) - Internal: [case](../syntax/ccmd/case.md)
- Internal: [while_loop](/syntax/ccmd/while_loop) - Internal: [while_loop](../syntax/ccmd/while_loop.md)
- POSIX - POSIX
[getopts(1)](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html#tag_20_54) [getopts(1)](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html#tag_20_54)
and and

View File

@ -653,7 +653,7 @@ recommendations:
<!-- --> <!-- -->
``` ```
- **Never** use the Csh `&>foo` and `>&foo` shorthand redirects. Use - **Never** use the Csh `&>foo` and `>&foo` shorthand redirects. Use
the long form `>foo 2>&1`. (see: [obsolete](obsolete)) the long form `>foo 2>&1`. (see: [obsolete](../obsolete.md))
```{=html} ```{=html}
<!-- --> <!-- -->
@ -694,4 +694,4 @@ The last example comes from this post:
# See also # See also
- Internal: [Redirection syntax overview](/syntax/redirection) - Internal: [Redirection syntax overview](../syntax/redirection.md)

View File

@ -6,7 +6,7 @@ This information was taken from a Bash version \"`4.1`\", every now and
then new options are added, so likely, this list isn\'t complete. then new options are added, so likely, this list isn\'t complete.
The shell-options can be set with the [shopt builtin The shell-options can be set with the [shopt builtin
command](/commands/builtin/shopt). command](../commands/builtin/shopt.md).
## Shell options ## Shell options
@ -78,8 +78,8 @@ stopped.
If set, Bash checks the window size after each command and, if If set, Bash checks the window size after each command and, if
necessary, updates the values of the variables necessary, updates the values of the variables
[LINES](/syntax/shellvars#LINES) and [LINES](../syntax/shellvars.md#LINES) and
[COLUMNS](/syntax/shellvars#COLUMNS). [COLUMNS](../syntax/shellvars.md#COLUMNS).
### cmdhist ### cmdhist
@ -174,7 +174,7 @@ match a glob.
Shell mode: all Default: off Shell mode: all Default: off
If set, Bash includes filenames beginning with a `.` (dot) in the If set, Bash includes filenames beginning with a `.` (dot) in the
results of [pathname expansion](/syntax/expansion/globs). results of [pathname expansion](../syntax/expansion/globs.md).
### execfail ### execfail
@ -209,7 +209,7 @@ If set, behavior intended for use by debuggers is enabled.
------------- ----------- ---------- ------------- ------------- ----------- ---------- -------------
Shell mode: all Default: off Shell mode: all Default: off
If set, the extended [pattern matching](/syntax/pattern) features are If set, the extended [pattern matching](../syntax/pattern.md) features are
enabled. See the important note below under [Parser enabled. See the important note below under [Parser
configurations](#parser_configurations). configurations](#parser_configurations).
@ -220,7 +220,7 @@ configurations](#parser_configurations).
Shell mode: all Default: on Shell mode: all Default: on
If set, `$'string'` and `$"string"` quoting is performed within If set, `$'string'` and `$"string"` quoting is performed within
[parameter expansions](/syntax/pe) enclosed in double quotes. See the [parameter expansions](../syntax/pe.md) enclosed in double quotes. See the
important note below under [Parser important note below under [Parser
configurations](#parser_configurations). configurations](#parser_configurations).
@ -240,7 +240,7 @@ result in an error message.
Shell mode: interactive Default: on Shell mode: interactive Default: on
If set, the suffixes specified by the If set, the suffixes specified by the
[FIGNORE](/syntax/shellvars#FIGNORE) shell variable cause words to be [FIGNORE](../syntax/shellvars.md#FIGNORE) shell variable cause words to be
ignored when performing word completion even if the ignored words are ignored when performing word completion even if the ignored words are
the only possible completions. This option is enabled by default. the only possible completions. This option is enabled by default.
@ -280,7 +280,7 @@ message format\".
Shell mode: interactive (?) Default: off Shell mode: interactive (?) Default: off
If set, the history list is appended to the file named by the value of If set, the history list is appended to the file named by the value of
the [HISTFILE](/syntax/shellvars#HISTFILE) variable when the shell the [HISTFILE](../syntax/shellvars.md#HISTFILE) variable when the shell
exits, rather than overwriting the file. exits, rather than overwriting the file.
### histreedit ### histreedit
@ -324,7 +324,7 @@ interactive login shell exits.
------------- ------------------------ ---------- --------- ------------- ------------------------ ---------- ---------
Shell mode: interactive Default: on Shell mode: interactive Default: on
Allow [commenting](/scripting/basics#comments) in interactive shells, on Allow [commenting](../scripting/basics.md#comments) in interactive shells, on
by default. by default.
### lastpipe ### lastpipe
@ -505,5 +505,5 @@ parsed:
## See also ## See also
- Internal: [shopt builtin command](/commands/builtin/shopt) - Internal: [shopt builtin command](../commands/builtin/shopt.md)
- Internal: [set builtin command](/commands/builtin/set) - Internal: [set builtin command](../commands/builtin/set.md)

View File

@ -67,7 +67,7 @@ conforming to the POSIX(r) standard as well. The profile files read are
`/etc/profile` and `~/.profile`, if it\'s a login shell. `/etc/profile` and `~/.profile`, if it\'s a login shell.
If it\'s not a login shell, the environment variable If it\'s not a login shell, the environment variable
[ENV](/syntax/shellvars#ENV) is evaluated and the resulting filename is [ENV](../syntax/shellvars.md#ENV) is evaluated and the resulting filename is
used as the name of the startup file. used as the name of the startup file.
After the startup files are read, Bash enters the [POSIX(r) compatiblity After the startup files are read, Bash enters the [POSIX(r) compatiblity
@ -83,7 +83,7 @@ mode (for running, not for starting!)](#posix_run_mode).
When Bash is started in POSIX(r) mode, it follows the POSIX(r) standard When Bash is started in POSIX(r) mode, it follows the POSIX(r) standard
for startup files. In this mode, **interactive shells** expand the for startup files. In this mode, **interactive shells** expand the
[ENV](/syntax/shellvars#ENV) variable and commands are read and executed [ENV](../syntax/shellvars.md#ENV) variable and commands are read and executed
from the file whose name is the expanded value.\ from the file whose name is the expanded value.\
No other startup files are read. Hence, a non-interactive shell doesn\'t No other startup files are read. Hence, a non-interactive shell doesn\'t
read any startup files in POSIX(r) mode. read any startup files in POSIX(r) mode.
@ -92,7 +92,7 @@ read any startup files in POSIX(r) mode.
- the commandline option `--posix` is specified - the commandline option `--posix` is specified
- the environment variable - the environment variable
[POSIXLY_CORRECT](/syntax/shellvars#POSIXLY_CORRECT) is set [POSIXLY_CORRECT](../syntax/shellvars.md#POSIXLY_CORRECT) is set
### Quick startup file reference ### Quick startup file reference
@ -301,12 +301,12 @@ FIXME help me to find out what breaks in POSIX(r) mode!
- Bash starting as `sh` (the basename of `argv[0]` is `sh`) - Bash starting as `sh` (the basename of `argv[0]` is `sh`)
- starting Bash with the commandline option `--posix` - starting Bash with the commandline option `--posix`
- on startup, the environment variable - on startup, the environment variable
[POSIXLY_CORRECT](/syntax/shellvars#POSIXLY_CORRECT) is set [POSIXLY_CORRECT](../syntax/shellvars.md#POSIXLY_CORRECT) is set
- the command `set -o posix` - the command `set -o posix`
[**Tests for the POSIX(r) mode:**]{.underline} [**Tests for the POSIX(r) mode:**]{.underline}
- the variable [SHELLOPTS](/syntax/shellvars#SHELLOPTS) contains - the variable [SHELLOPTS](../syntax/shellvars.md#SHELLOPTS) contains
`posix` in its list `posix` in its list
### Restricted shell ### Restricted shell
@ -316,9 +316,9 @@ far more controlled and limited than the standard shell mode. It acts
like normal Bash with the following restrictions: like normal Bash with the following restrictions:
- the `cd` command can\'t be used to change directories - the `cd` command can\'t be used to change directories
- the variables [SHELL](/syntax/shellvars#SHELL), - the variables [SHELL](../syntax/shellvars.md#SHELL),
[PATH](/syntax/shellvars#PATH), [ENV](/syntax/shellvars#ENV) and [PATH](../syntax/shellvars.md#PATH), [ENV](../syntax/shellvars.md#ENV) and
[BASH_ENV](/syntax/shellvars#BASH_ENV) can\'t be set or unset [BASH_ENV](../syntax/shellvars.md#BASH_ENV) can\'t be set or unset
- command names that contain a `/` (slash) can\'t be called (hence - command names that contain a `/` (slash) can\'t be called (hence
you\'re limited to `PATH`) you\'re limited to `PATH`)
- filenames containing a `/` (slash) can\'t be specified as argument - filenames containing a `/` (slash) can\'t be specified as argument
@ -327,7 +327,7 @@ like normal Bash with the following restrictions:
to the `-p` option of the `hash` builtin command to the `-p` option of the `hash` builtin command
- function definitions are not inherited from the environment at shell - function definitions are not inherited from the environment at shell
startup startup
- the environment variable [SHELLOPTS](/syntax/shellvars#SHELLOPTS) is - the environment variable [SHELLOPTS](../syntax/shellvars.md#SHELLOPTS) is
ignored at startup ignored at startup
- redirecting output using the `>`, `>|`, `<>`, `>&`, `&>`, and `>>` - redirecting output using the `>`, `>|`, `<>`, `>&`, `&>`, and `>>`
redirection operators isn\'t allowed redirection operators isn\'t allowed

View File

@ -19,8 +19,8 @@ Note that the `shopt` builtin command first appeared in Bash 2.0.
For this topic, see also For this topic, see also
- [shell_options](/internals/shell_options) - [shell_options](../internals/shell_options.md)
- [set](/commands/builtin/set) - [set](../commands/builtin/set.md)
Feature or change description Appeared in Bash version See also/remarks Feature or change description Appeared in Bash version See also/remarks
--------------------------------- -------------------------- --------------------------------------------------------------------------------- --------------------------------- -------------------------- ---------------------------------------------------------------------------------
@ -77,7 +77,7 @@ For this topic, see also
For this topic, see also For this topic, see also
- [printf](/commands/builtin/printf) - [printf](../commands/builtin/printf.md)
Feature or change description Appeared in Bash version See also/remarks Feature or change description Appeared in Bash version See also/remarks
------------------------------------------------------------- -------------------------- -------------------------------------------------------- ------------------------------------------------------------- -------------------------- --------------------------------------------------------
@ -98,8 +98,8 @@ For this topic, see also
For this topic, see also For this topic, see also
- [conditional_expression](/syntax/ccmd/conditional_expression) - [conditional_expression](../syntax/ccmd/conditional_expression.md)
- [classictest](/commands/classictest) - [classictest](../commands/classictest.md)
Feature or change description Appeared in Bash version See also/remarks Feature or change description Appeared in Bash version See also/remarks
-------------------------------------------------------------------- -------------------------- -------------------------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------- --------------------------------------------------------------------------------------
@ -121,23 +121,23 @@ For this topic, see also
`bashbug` new 1.14.0 `bashbug` new 1.14.0
`select` new 1.14.0 `select` new 1.14.0
`disown` new 2.0 `disown` new 2.0
`shopt` new 2.0 [shopt](/commands/builtin/shopt) `shopt` new 2.0 [shopt](../commands/builtin/shopt.md)
`declare` new options `-a` and `-F` 2.0 `declare` new options `-a` and `-F` 2.0
`enable` builtin has basic plugin support (dlopen) 2.0 `enable` builtin has basic plugin support (dlopen) 2.0
`exec` options `-l`, `-c` and `-a` 2.0 `exec` options `-l`, `-c` and `-a` 2.0
`read` options `-p`, `-e` and `-a` 2.0 [read](/commands/builtin/read) `read` options `-p`, `-e` and `-a` 2.0 [read](../commands/builtin/read.md)
`readonly` option `-a` 2.0 [arrays](/syntax/arrays) `readonly` option `-a` 2.0 [arrays](../syntax/arrays.md)
`time` new keyword 2.0 `time` new keyword 2.0
`shopt` `-p` (reusable output) 2.02 `shopt` `-p` (reusable output) 2.02
`umask` `-p` (reusable output) 2.02 `umask` `-p` (reusable output) 2.02
`complete` new 2.04-devel for and together with support for programmable completion `complete` new 2.04-devel for and together with support for programmable completion
`compgen` new 2.04-devel for and together with support for programmable completion `compgen` new 2.04-devel for and together with support for programmable completion
`read` options `-t`, `-n`, `-d`, `-s` 2.04-devel [read](/commands/builtin/read) `read` options `-t`, `-n`, `-d`, `-s` 2.04-devel [read](../commands/builtin/read.md)
`for ((...;...;...))` new 2.04-devel KSH93 `for ((...;...;...))` new 2.04-devel KSH93
`set` print shell functions in a format reusable as input 2.05-beta1 `set` print shell functions in a format reusable as input 2.05-beta1
`for` allow an empty word list 2.05a-alpha1 `for` allow an empty word list 2.05a-alpha1
`read` new option `-u` 2.05b-alpha1 [read](/commands/builtin/read) `read` new option `-u` 2.05b-alpha1 [read](../commands/builtin/read.md)
`caller` new 3.0 [caller](/commands/builtin/caller) `caller` new 3.0 [caller](../commands/builtin/caller.md)
`coproc` new 4.0-alpha `coproc` new 4.0-alpha
`declare` new options `-l` and `-u` 4.0-alpha together with case-changing expansion forms `declare` new options `-l` and `-u` 4.0-alpha together with case-changing expansion forms
`case` new action list terminators \'\';;& and \'\';& 4.0-alpha ksh93: only `;&`. zsh and mksh: `;|`. mksh: all 4, (`;;&` is undocumented Bash compatibility) `case` new action list terminators \'\';;& and \'\';& 4.0-alpha ksh93: only `;&`. zsh and mksh: `;|`. mksh: all 4, (`;;&` is undocumented Bash compatibility)
@ -170,7 +170,7 @@ For this topic, see also
`history` option `-d` allows negative numbers to index from the end of the history list 5.0-alpha `history` option `-d` allows negative numbers to index from the end of the history list 5.0-alpha
`umask` allows modes greater than octal 777 5.0-alpha `umask` allows modes greater than octal 777 5.0-alpha
`times` honors current locale settings when printing decimal points 5.0-alpha `times` honors current locale settings when printing decimal points 5.0-alpha
`kill` New options `-n SIGNUMBER` and `-s SIGNAME` 5.0-beta2 [kill](/commands/builtin/kill) `kill` New options `-n SIGNUMBER` and `-s SIGNAME` 5.0-beta2 [kill](../commands/builtin/kill.md)
`select` Support for an empty wordlist following `in` 5.0-beta2 `select` Support for an empty wordlist following `in` 5.0-beta2
`read` Option `-e` (use ReadLine to obtain input) now works with arbitrary file descriptors (given by `-u` option) 5.1-alpha `read` Option `-e` (use ReadLine to obtain input) now works with arbitrary file descriptors (given by `-u` option) 5.1-alpha
`trap` `-p` option prints signals with SIG_DFL/SIG_IGN on shell start (POSIX mode) 5.1-alpha `trap` `-p` option prints signals with SIG_DFL/SIG_IGN on shell start (POSIX mode) 5.1-alpha
@ -241,7 +241,7 @@ For this topic, see also
For this topic, see also For this topic, see also
- [pe](/syntax/pe). - [pe](../syntax/pe.md).
Feature or change description Appeared in Bash version Remarks Feature or change description Appeared in Bash version Remarks
------------------------------------------------------------------------------------------------------ -------------------------- --------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------ -------------------------- ---------------------------------------------------------------------------------------------------------------
@ -282,8 +282,8 @@ For this topic, see also
For this topic, see also For this topic, see also
- [arith_expr](/syntax/arith_expr) - [arith_expr](../syntax/arith_expr.md)
- [arith](/syntax/expansion/arith) - [arith](../syntax/expansion/arith.md)
Feature or change description Appeared in Bash version Remarks Feature or change description Appeared in Bash version Remarks
-------------------------------------------- -------------------------- ------------------------------------------- -------------------------------------------- -------------------------- -------------------------------------------
@ -299,7 +299,7 @@ For this topic, see also
For this topic, see also For this topic, see also
- [redirection](/syntax/redirection) - [redirection](../syntax/redirection.md)
Feature or change description Appeared in Bash version Remarks Feature or change description Appeared in Bash version Remarks
--------------------------------------------------------------------------------------- -------------------------- --------- --------------------------------------------------------------------------------------- -------------------------- ---------

View File

@ -71,7 +71,7 @@ interpreter specified by the shebang. \</WRAP\>
**Additional note:** When you specify `#!/bin/sh` as shebang and that\'s **Additional note:** When you specify `#!/bin/sh` as shebang and that\'s
a link to a Bash, then Bash will run in POSIX(r) mode! See: a link to a Bash, then Bash will run in POSIX(r) mode! See:
- [Bash behaviour](/scripting/bashbehaviour). - [Bash behaviour](../scripting/bashbehaviour.md).
A common method is to specify a shebang like A common method is to specify a shebang like
@ -113,7 +113,7 @@ When you write a script:
To learn more about the standard filedescriptors, especially about To learn more about the standard filedescriptors, especially about
redirection and piping, see: redirection and piping, see:
- [An illustrated redirection tutorial](/howto/redirection_tutorial) - [An illustrated redirection tutorial](../howto/redirection_tutorial.md)
## Variable names ## Variable names
@ -184,7 +184,7 @@ else
fi fi
``` ```
Read more about [the test command](/commands/classictest) Read more about [the test command](../commands/classictest.md)
A common exit code check method uses the \"`||`\" or \"`&&`\" operators. A common exit code check method uses the \"`||`\" or \"`&&`\" operators.
This lets you execute a command based on whether or not the previous This lets you execute a command based on whether or not the previous
@ -247,7 +247,7 @@ it, effectively, the entire block was ignored.
The here-document-tag was quoted here **to avoid substitutions** in the The here-document-tag was quoted here **to avoid substitutions** in the
\"commented\" text! Check [redirection with \"commented\" text! Check [redirection with
here-documents](/syntax/redirection#tag_heredoc) for more here-documents](../syntax/redirection.md#tag_heredoc) for more
## Variable scope ## Variable scope
@ -279,7 +279,7 @@ program\".
for example a *subshell*, they will be set there, but you will **never** for example a *subshell*, they will be set there, but you will **never**
have access to them outside of that subshell. One way to create a have access to them outside of that subshell. One way to create a
subshell is the pipe. It\'s all mentioned in a small article about [Bash subshell is the pipe. It\'s all mentioned in a small article about [Bash
in the processtree](/scripting/processtree)! in the processtree](../scripting/processtree.md)!
### Local variables ### Local variables
@ -352,6 +352,6 @@ export myvariable
Remember that the *exported* variable is a **copy**. There is no Remember that the *exported* variable is a **copy**. There is no
provision to \"copy it back to the parent.\" See the article about [Bash provision to \"copy it back to the parent.\" See the article about [Bash
in the process tree](/scripting/processtree)! in the process tree](../scripting/processtree.md)!
[^1]: under specific circumstances, also by the shell itself [^1]: under specific circumstances, also by the shell itself

View File

@ -55,13 +55,13 @@ Insert **echos** everywhere you can, and print to `stderr`:
echo "DEBUG: current i=$i" >&2 echo "DEBUG: current i=$i" >&2
If you read input from **anywhere**, such as a file or [command If you read input from **anywhere**, such as a file or [command
substitution](/syntax/expansion/cmdsubst), print the debug output with substitution](../syntax/expansion/cmdsubst.md), print the debug output with
literal quotes, to see leading and trailing spaces! literal quotes, to see leading and trailing spaces!
pid=$(< fooservice.pid) pid=$(< fooservice.pid)
echo "DEBUG: read from file: pid=\"$pid\"" >&2 echo "DEBUG: read from file: pid=\"$pid\"" >&2
Bash\'s [printf](/commands/builtin/printf) command has the `%q` format, Bash\'s [printf](../commands/builtin/printf.md) command has the `%q` format,
which is handy for verifying whether strings are what they appear to be. which is handy for verifying whether strings are what they appear to be.
foo=$(< inputfile) foo=$(< inputfile)
@ -77,18 +77,18 @@ There are two useful debug outputs for that task (both are written to
- print commands to be executed to `stderr` as if they were read - print commands to be executed to `stderr` as if they were read
from input (script file or keyboard) from input (script file or keyboard)
- print everything **before** any ([substitution and - print everything **before** any ([substitution and
expansion](/syntax/expansion/intro), \...) is applied expansion](../syntax/expansion/intro.md), \...) is applied
- `set -x` mode (`set -o xtrace`) - `set -x` mode (`set -o xtrace`)
- print everything as if it were executed, after [substitution and - print everything as if it were executed, after [substitution and
expansion](/syntax/expansion/intro) is applied expansion](../syntax/expansion/intro.md) is applied
- indicate the depth-level of the subshell (by default by - indicate the depth-level of the subshell (by default by
prefixing a `+` (plus) sign to the displayed command) prefixing a `+` (plus) sign to the displayed command)
- indicate the recognized words after [word - indicate the recognized words after [word
splitting](/syntax/expansion/wordsplit) by marking them like splitting](../syntax/expansion/wordsplit.md) by marking them like
`'x y'` `'x y'`
- in shell version 4.1, this debug output can be printed to a - in shell version 4.1, this debug output can be printed to a
configurable file descriptor, rather than sdtout by setting the configurable file descriptor, rather than sdtout by setting the
[BASH_XTRACEFD](/syntax/shellvars#BASH_XTRACEFD) variable. [BASH_XTRACEFD](../syntax/shellvars.md#BASH_XTRACEFD) variable.
**[Hint:]{.underline}** These modes can be entered when calling Bash: **[Hint:]{.underline}** These modes can be entered when calling Bash:
@ -98,7 +98,7 @@ There are two useful debug outputs for that task (both are written to
### Simple example of how to interpret xtrace output ### Simple example of how to interpret xtrace output
Here\'s a simple command (a string comparison using the [classic test Here\'s a simple command (a string comparison using the [classic test
command](/commands/classictest)) executed while in `set -x` mode: command](../commands/classictest.md)) executed while in `set -x` mode:
set -x set -x
foo="bar baz" foo="bar baz"
@ -126,7 +126,7 @@ MESSAGES ;) ). Let\'s check it\...
(by AnMaster) (by AnMaster)
`xtrace` output would be more useful if it contained source file and `xtrace` output would be more useful if it contained source file and
line number. Add this assignment [PS4](/syntax/shellvars#PS4) at the line number. Add this assignment [PS4](../syntax/shellvars.md#PS4) at the
beginning of your script to enable the inclusion of that information: beginning of your script to enable the inclusion of that information:
export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
@ -220,7 +220,7 @@ This can be wrapped in a shell function for more readable code.
Usually indicates exactly what it says: An unexpected end of file. It\'s Usually indicates exactly what it says: An unexpected end of file. It\'s
unexpected because Bash waits for the closing of a [compound unexpected because Bash waits for the closing of a [compound
command](/syntax/ccmd/intro): command](../syntax/ccmd/intro.md):
- did you close your `do` with a `done`? - did you close your `do` with a `done`?
- did you close your `if` with a `fi`? - did you close your `if` with a `fi`?
@ -231,7 +231,7 @@ command](/syntax/ccmd/intro):
**[Note:]{.underline}** It seems that here-documents (tested on versions **[Note:]{.underline}** It seems that here-documents (tested on versions
`1.14.7`, `2.05b`, `3.1.17` and `4.0`) are correctly terminated when `1.14.7`, `2.05b`, `3.1.17` and `4.0`) are correctly terminated when
there is an EOF before the end-of-here-document tag (see there is an EOF before the end-of-here-document tag (see
[redirection](/syntax/redirection)). The reason is unknown, but it seems [redirection](../syntax/redirection.md)). The reason is unknown, but it seems
to be deliberate. Bash 4.0 added an extra message for this: to be deliberate. Bash 4.0 added an extra message for this:
`` warning: here-document at line <N> delimited by end-of-file (wanted `<MARKER>') `` `` warning: here-document at line <N> delimited by end-of-file (wanted `<MARKER>') ``
@ -247,7 +247,7 @@ These *unmatched errors* occur with:
- double-quote pairs - double-quote pairs
- single-quote pairs (also `$'string'`!) - single-quote pairs (also `$'string'`!)
- missing a closing `}` with [parameter expansion syntax](/syntax/pe) - missing a closing `}` with [parameter expansion syntax](../syntax/pe.md)
### Too many arguments ### Too many arguments
@ -366,7 +366,7 @@ the possibility that`^M` is involved. Find and eliminate it! \</note\>
## See also ## See also
- [the set builtin command](/commands/builtin/set) (for `-v` and `-x`) - [the set builtin command](../commands/builtin/set.md) (for `-v` and `-x`)
FIXME FIXME

View File

@ -25,8 +25,8 @@ mode]{.underline}.
See also: See also:
- [Bash startup mode: SH mode](/scripting/bashbehaviour#sh_mode) - [Bash startup mode: SH mode](../scripting/bashbehaviour.md#sh_mode)
- [Bash run mode: POSIX mode](/scripting/bashbehaviour#posix_run_mode) - [Bash run mode: POSIX mode](../scripting/bashbehaviour.md#posix_run_mode)
### Your script named \"test\" doesn\'t execute ### Your script named \"test\" doesn\'t execute
@ -63,7 +63,7 @@ filename expansion happens **after** that, so there is a chance that
Please see: Please see:
- [brace](/syntax/expansion/brace) - [brace](../syntax/expansion/brace.md)
## Test-command ## Test-command
@ -74,7 +74,7 @@ Please see:
Please see: Please see:
- [The classic test command - - [The classic test command -
pitfalls](/commands/classictest#pitfalls_summarized) pitfalls](../commands/classictest.md#pitfalls_summarized)
## Variables ## Variables
@ -163,7 +163,7 @@ of the referenced variables/parameters. i.e. **not** (`$PATH`):
echo "The first character of PATH is ${PATH:0:1}" echo "The first character of PATH is ${PATH:0:1}"
Note that if you are using variables in [arithmetic Note that if you are using variables in [arithmetic
expressions](/syntax/arith_expr), then the bare **name** is allowed: expressions](../syntax/arith_expr.md), then the bare **name** is allowed:
((a=$a+7)) # Add 7 to a ((a=$a+7)) # Add 7 to a
((a = a + 7)) # Add 7 to a. Identical to the previous command. ((a = a + 7)) # Add 7 to a. Identical to the previous command.
@ -173,10 +173,10 @@ expressions](/syntax/arith_expr), then the bare **name** is allowed:
Please see: Please see:
- [words](/syntax/words) - [words](../syntax/words.md)
- [quoting](/syntax/quoting) - [quoting](../syntax/quoting.md)
- [wordsplit](/syntax/expansion/wordsplit) - [wordsplit](../syntax/expansion/wordsplit.md)
- [pe](/syntax/pe) - [pe](../syntax/pe.md)
### Exporting ### Exporting
@ -206,7 +206,7 @@ In this case, the export command is of no use.
Please see: Please see:
- [processtree](/scripting/processtree) - [processtree](../scripting/processtree.md)
## Exit codes ## Exit codes
@ -243,7 +243,7 @@ you need only a \"true/false\" exit indication, there\'s no need for
See also: See also:
- [Exit codes](/scripting/basics#exit_codes) - [Exit codes](../scripting/basics.md#exit_codes)
### Output vs. Return Value ### Output vs. Return Value
@ -277,6 +277,6 @@ Make sure you\'re using the form you intended:
Please see: Please see:
- [intro](/syntax/ccmd/intro) - [intro](../syntax/ccmd/intro.md)
- [cmdsubst](/syntax/expansion/cmdsubst) - [cmdsubst](../syntax/expansion/cmdsubst.md)
- [grouping_subshell](/syntax/ccmd/grouping_subshell) - [grouping_subshell](../syntax/ccmd/grouping_subshell.md)

View File

@ -8,7 +8,7 @@ syntax, with some extensions and derivations.
If scripts need to be portable, some of the BASH-specific syntax If scripts need to be portable, some of the BASH-specific syntax
elements should be avoided. Others should be avoided for all scripts, elements should be avoided. Others should be avoided for all scripts,
e.g. if there is a corresponding POSIX(r)-compatible syntax (see e.g. if there is a corresponding POSIX(r)-compatible syntax (see
[obsolete](/scripting/obsolete)). [obsolete](../scripting/obsolete.md)).
Some syntax elements have a BASH-specific, and a portable[^1]) pendant. Some syntax elements have a BASH-specific, and a portable[^1]) pendant.
In these cases the portable syntax should be preferred. In these cases the portable syntax should be preferred.
@ -26,7 +26,7 @@ In these cases the portable syntax should be preferred.
`(( MATH ))` `: $(( MATH ))` POSIX(r) does\'t define an arithmetic compund command, many shells don\'t know it. Using the pseudo-command `:` and the arithmetic expansion `$(( ))` is a kind of workaround here. **Attention:** Not all shell support assignment like `$(( a = 1 + 1 ))`! Also see below for a probably more portable solution. all POSIX(r) compatible shells `(( MATH ))` `: $(( MATH ))` POSIX(r) does\'t define an arithmetic compund command, many shells don\'t know it. Using the pseudo-command `:` and the arithmetic expansion `$(( ))` is a kind of workaround here. **Attention:** Not all shell support assignment like `$(( a = 1 + 1 ))`! Also see below for a probably more portable solution. all POSIX(r) compatible shells
`[[\ EXPRESSION\ ]]` `[ EXPRESSION ]`\ The Bashish test keyword is reserved by POSIX(r), but not defined. Use the old fashioned way with the `test` command. See [the classic test command](/commands/classictest) POSIX(r) and others `[[\ EXPRESSION\ ]]` `[ EXPRESSION ]`\ The Bashish test keyword is reserved by POSIX(r), but not defined. Use the old fashioned way with the `test` command. See [the classic test command](../commands/classictest.md) POSIX(r) and others
or\ or\
`test EXPRESSION` `test EXPRESSION`
@ -98,7 +98,7 @@ Why? (list of known behaviours)
variables or the build options, especially KSH93 and Bash) variables or the build options, especially KSH93 and Bash)
For these, and possibly other, reasons, POSIX (SUS) standardized the For these, and possibly other, reasons, POSIX (SUS) standardized the
existance of [the `printf` command](/commands/builtin/printf). existance of [the `printf` command](../commands/builtin/printf.md).
### Parameter expansions ### Parameter expansions
@ -112,7 +112,7 @@ existance of [the `printf` command](/commands/builtin/printf).
#### PWD #### PWD
[PWD](/syntax/shellvars#PWD) is POSIX but not Bourne. Most shells are [PWD](../syntax/shellvars.md#PWD) is POSIX but not Bourne. Most shells are
*not POSIX* in that they don\'t ignore the value of the `PWD` *not POSIX* in that they don\'t ignore the value of the `PWD`
environment variable. Workaround to fix the value of `PWD` at the start environment variable. Workaround to fix the value of `PWD` at the start
of your script: of your script:
@ -121,7 +121,7 @@ of your script:
#### RANDOM #### RANDOM
[RANDOM](/syntax/shellvars#RANDOM) is Bash/KSH/ZSH specific variable [RANDOM](../syntax/shellvars.md#RANDOM) is Bash/KSH/ZSH specific variable
that will give you a random number up to 32767 (2\^15-1). Among many that will give you a random number up to 32767 (2\^15-1). Among many
other available external options, you can use awk to generate a random other available external options, you can use awk to generate a random
number. There are multiple implementations of awk and which version your number. There are multiple implementations of awk and which version your
@ -147,12 +147,12 @@ complaining about possible stupid code!*
#### SECONDS #### SECONDS
[SECONDS](/syntax/shellvars#SECONDS) is KSH/ZSH/Bash specific. Avoid it. [SECONDS](../syntax/shellvars.md#SECONDS) is KSH/ZSH/Bash specific. Avoid it.
Find another method. Find another method.
### Check for a command in PATH ### Check for a command in PATH
The [PATH](/syntax/shellvars#PATH) variable is a colon-delimited list of The [PATH](../syntax/shellvars.md#PATH) variable is a colon-delimited list of
directory names, so it\'s basically possible to run a loop and check directory names, so it\'s basically possible to run a loop and check
every `PATH` component for the command you\'re looking for and for every `PATH` component for the command you\'re looking for and for
executability. executability.

View File

@ -5,7 +5,7 @@
This (incomplete) page describes some syntax and commands considered This (incomplete) page describes some syntax and commands considered
obsolete by some measure. A thorough discussion of the rationale is obsolete by some measure. A thorough discussion of the rationale is
beyond the scope of this page. See the [portability beyond the scope of this page. See the [portability
page](/scripting/nonportable) for a discussion on portability issues. page](../scripting/nonportable.md) for a discussion on portability issues.
This first table lists syntax that is tolerated by Bash but has few if This first table lists syntax that is tolerated by Bash but has few if
any legitimate uses. These features exist mostly for Bourne, csh, or any legitimate uses. These features exist mostly for Bourne, csh, or
@ -18,9 +18,9 @@ of POSIX, and some may be incompatible with POSIX.
Syntax Replacement Description Syntax Replacement Description
---------------------------------- --------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------- --------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`&>FILE` and `>&FILE` `>FILE 2>&1` This redirection syntax is short for `>FILE 2>&1` and originates in the C Shell. The latter form is especially uncommon and should never be used, and the explicit form using separate redirections is preferred over both. These shortcuts contribute to confusion about the copy descriptor because the syntax is unclear. They also introduce parsing ambiguity, and conflict with POSIX. Shells without this feature treat `cmd1 &>file cmd2` as: \"background `cmd1` and then execute `cmd2` with its stdout redirected to `file`\", which is the correct interpretation of this expression. See: [redirection](/syntax/redirection) \`\$ { bash; dash \</dev/fd/0; } \<\<\<\'echo foo\>/dev/null&\>/dev/fd/2 echo bar\' foo echo bar bar\` `&>FILE` and `>&FILE` `>FILE 2>&1` This redirection syntax is short for `>FILE 2>&1` and originates in the C Shell. The latter form is especially uncommon and should never be used, and the explicit form using separate redirections is preferred over both. These shortcuts contribute to confusion about the copy descriptor because the syntax is unclear. They also introduce parsing ambiguity, and conflict with POSIX. Shells without this feature treat `cmd1 &>file cmd2` as: \"background `cmd1` and then execute `cmd2` with its stdout redirected to `file`\", which is the correct interpretation of this expression. See: [redirection](../syntax/redirection.md) \`\$ { bash; dash \</dev/fd/0; } \<\<\<\'echo foo\>/dev/null&\>/dev/fd/2 echo bar\' foo echo bar bar\`
`$[EXPRESSION]` `$((EXPRESSION))` This undocumented syntax is completely replaced by the POSIX-conforming arithmetic expansion `$((EXPRESSION))`. It is unimplemented almost everywhere except Bash and Zsh. See [arithmetic expansion](/syntax/expansion/arith). [Some discussion](http://lists.gnu.org/archive/html/bug-bash/2012-04/msg00034.html). `$[EXPRESSION]` `$((EXPRESSION))` This undocumented syntax is completely replaced by the POSIX-conforming arithmetic expansion `$((EXPRESSION))`. It is unimplemented almost everywhere except Bash and Zsh. See [arithmetic expansion](../syntax/expansion/arith.md). [Some discussion](http://lists.gnu.org/archive/html/bug-bash/2012-04/msg00034.html).
`COMMAND\ |&\ COMMAND` `COMMAND 2>&1 | COMMAND` This is an alternate pipeline operator derived from Zsh. Officially, it is not considered deprecated by Bash, but I highly discourage it. It conflicts with the list operator used for [coprocess](/syntax/keywords/coproc) creation in most Korn shells. It also has confusing behavior. The stdout is redirected first like an ordinary pipe, while the stderr is actually redirected last \-- after other redirects preceding the pipe operator. Overall, it\'s pointless syntax bloat. Use an explicit redirect instead. `COMMAND\ |&\ COMMAND` `COMMAND 2>&1 | COMMAND` This is an alternate pipeline operator derived from Zsh. Officially, it is not considered deprecated by Bash, but I highly discourage it. It conflicts with the list operator used for [coprocess](../syntax/keywords/coproc.md) creation in most Korn shells. It also has confusing behavior. The stdout is redirected first like an ordinary pipe, while the stderr is actually redirected last \-- after other redirects preceding the pipe operator. Overall, it\'s pointless syntax bloat. Use an explicit redirect instead.
`function\ NAME()\ COMPOUND-CMD` `NAME()\ COMPOUND-CMD` or `function\ NAME\ {\ CMDS;\ }` This is an amalgamation between the Korn and POSIX style function definitions - using both the `function` keyword and parentheses. It has no useful purpose and no historical basis or reason to exist. It is not specified by POSIX. It is accepted by Bash, mksh, zsh, and perhaps some other Korn shells, where it is treated as identical to the POSIX-style function. It is not accepted by AT&T ksh. It should never be used. See the next table for the `function` keyword. Bash doesn\'t have this feature documented as expressly deprecated. `function\ NAME()\ COMPOUND-CMD` `NAME()\ COMPOUND-CMD` or `function\ NAME\ {\ CMDS;\ }` This is an amalgamation between the Korn and POSIX style function definitions - using both the `function` keyword and parentheses. It has no useful purpose and no historical basis or reason to exist. It is not specified by POSIX. It is accepted by Bash, mksh, zsh, and perhaps some other Korn shells, where it is treated as identical to the POSIX-style function. It is not accepted by AT&T ksh. It should never be used. See the next table for the `function` keyword. Bash doesn\'t have this feature documented as expressly deprecated.
`for x; { ...;}` `do`, `done`, `in`, `esac`, etc. This undocumented syntax replaces the `do` and `done` reserved words with braces. Many Korn shells support various permutations on this syntax for certain compound commands like `for`, `case`, and `while`. Which ones and certain details like whether a newline or semicolon are required vary. Only `for` works in Bash. Needless to say, don\'t use it. `for x; { ...;}` `do`, `done`, `in`, `esac`, etc. This undocumented syntax replaces the `do` and `done` reserved words with braces. Many Korn shells support various permutations on this syntax for certain compound commands like `for`, `case`, and `while`. Which ones and certain details like whether a newline or semicolon are required vary. Only `for` works in Bash. Needless to say, don\'t use it.
@ -34,11 +34,11 @@ historical reasons.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Syntax Replacement Description Syntax Replacement Description
----------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Unquoted expansions, [wordsplit](/syntax/expansion/wordsplit), and [globs](/syntax/expansion/globs) [Proper quoting](http://mywiki.wooledge.org/Quotes), Ksh/Bash-style [arrays](/syntax/arrays), The \"\$@\" expansion, [read](/commands/builtin/read) *Quoting errors* are a broad category of common mistakes brought about by a few unintuitive features carried over from the Bourne shell due to complaints of broken scripts and changes in previously documented behavior. Most of the important expansions are performed at the same time from left to right. However, a few expansions, most notably word-splitting and globbing, and in shells other than Bash, [brace expansion](/syntax/expansion/brace), are performed **on the results of previous expansions, by default, unless they are quoted.** This means that the act of expanding an unquoted variable in an ordinary argument context, depending on the value of the variable, can yield different results depending on possibly uncontrolled side-effects like the value of `IFS`, and the names of files in the current working directory. You can\'t get globbing without word-splitting, or vice versa (without `set -f`). [You can\'t store a command or character-delimited list in a variable and safely evaluate it with unquoted expansion](http://mywiki.wooledge.org/BashFAQ/050). If possible, always choose a shell that supports Korn shell arrays such as Bash. They are a vital but non-standard feature for writing clean, safe scripts. Well-written scripts don\'t use word-splitting. A few exceptions are listed on the [word splitting page](/syntax/expansion/wordsplit). A significant proportion of the issues on the famous [Pitfalls list](http://mywiki.wooledge.org/BashPitfalls) fall under this category. See also: *[Don\'t read lines with for!](http://mywiki.wooledge.org/DontReadLinesWithFor)* Unquoted expansions, [wordsplit](../syntax/expansion/wordsplit.md), and [globs](../syntax/expansion/globs.md) [Proper quoting](http://mywiki.wooledge.org/Quotes), Ksh/Bash-style [arrays](../syntax/arrays.md), The \"\$@\" expansion, [read](../commands/builtin/read.md) *Quoting errors* are a broad category of common mistakes brought about by a few unintuitive features carried over from the Bourne shell due to complaints of broken scripts and changes in previously documented behavior. Most of the important expansions are performed at the same time from left to right. However, a few expansions, most notably word-splitting and globbing, and in shells other than Bash, [brace expansion](../syntax/expansion/brace.md), are performed **on the results of previous expansions, by default, unless they are quoted.** This means that the act of expanding an unquoted variable in an ordinary argument context, depending on the value of the variable, can yield different results depending on possibly uncontrolled side-effects like the value of `IFS`, and the names of files in the current working directory. You can\'t get globbing without word-splitting, or vice versa (without `set -f`). [You can\'t store a command or character-delimited list in a variable and safely evaluate it with unquoted expansion](http://mywiki.wooledge.org/BashFAQ/050). If possible, always choose a shell that supports Korn shell arrays such as Bash. They are a vital but non-standard feature for writing clean, safe scripts. Well-written scripts don\'t use word-splitting. A few exceptions are listed on the [word splitting page](../syntax/expansion/wordsplit.md). A significant proportion of the issues on the famous [Pitfalls list](http://mywiki.wooledge.org/BashPitfalls) fall under this category. See also: *[Don\'t read lines with for!](http://mywiki.wooledge.org/DontReadLinesWithFor)*
`` `COMMANDS` `` `$(COMMANDS)` This is the older Bourne-compatible form of the [command substitution](/syntax/expansion/cmdsubst). Both the `` `COMMANDS` `` and `$(COMMANDS)` syntaxes are specified by POSIX, but the latter is [greatly]{.underline} preferred, though the former is unfortunately still very prevalent in scripts. New-style command substitutions are widely implemented by every modern shell (and then some). The only reason for using backticks is for compatibility with a real Bourne shell (like Heirloom). Backtick command substitutions require special escaping when nested, and examples found in the wild are improperly quoted more often than not. See: *[Why is \$(\...) preferred over \`\...\` (backticks)?](http://mywiki.wooledge.org/BashFAQ/082)*. `` `COMMANDS` `` `$(COMMANDS)` This is the older Bourne-compatible form of the [command substitution](../syntax/expansion/cmdsubst.md). Both the `` `COMMANDS` `` and `$(COMMANDS)` syntaxes are specified by POSIX, but the latter is [greatly]{.underline} preferred, though the former is unfortunately still very prevalent in scripts. New-style command substitutions are widely implemented by every modern shell (and then some). The only reason for using backticks is for compatibility with a real Bourne shell (like Heirloom). Backtick command substitutions require special escaping when nested, and examples found in the wild are improperly quoted more often than not. See: *[Why is \$(\...) preferred over \`\...\` (backticks)?](http://mywiki.wooledge.org/BashFAQ/082)*.
`[\ EXPRESSION\ ]`\\ and\\ `test\ EXPRESSION` `[[\ EXPRESSION\ ]]` `test` and `[` are the Bourne/POSIX commands for evaluating test expressions (they are almost identical, and `[` is somewhat more common). The expressions consist of regular arguments, unlike the Ksh/Bash `[[` command. While the issue is analogous to `let` vs `((`, the advantages of `[[` vs `[` are even more important because the arguments/expansions aren\'t just concatenated into one expression. With the classic `[` command, the number of arguments is significant. If at all possible, use the [conditional expression](/syntax/ccmd/conditional_expression) (\"new test command\") `[[ EXPRESSION ]]`. Unless there is a need for POSIX compatibility, there are only a few reasons to use `[`. `[[` is one of the most portable and consistent non-POSIX ksh extensions available. See: [conditional_expression](/syntax/ccmd/conditional_expression) and *[What is the difference between test, \[ and \[\[ ?](http://mywiki.wooledge.org/BashFAQ/031)* `[\ EXPRESSION\ ]`\\ and\\ `test\ EXPRESSION` `[[\ EXPRESSION\ ]]` `test` and `[` are the Bourne/POSIX commands for evaluating test expressions (they are almost identical, and `[` is somewhat more common). The expressions consist of regular arguments, unlike the Ksh/Bash `[[` command. While the issue is analogous to `let` vs `((`, the advantages of `[[` vs `[` are even more important because the arguments/expansions aren\'t just concatenated into one expression. With the classic `[` command, the number of arguments is significant. If at all possible, use the [conditional expression](../syntax/ccmd/conditional_expression.md) (\"new test command\") `[[ EXPRESSION ]]`. Unless there is a need for POSIX compatibility, there are only a few reasons to use `[`. `[[` is one of the most portable and consistent non-POSIX ksh extensions available. See: [conditional_expression](../syntax/ccmd/conditional_expression.md) and *[What is the difference between test, \[ and \[\[ ?](http://mywiki.wooledge.org/BashFAQ/031)*
`set -e`, `set -o errexit`\ proper control flow and error handling `set -e` causes untested non-zero exit statuses to be fatal. It is a debugging feature intended for use only during development and should not be used in production code, especially init scripts and other high-availability scripts. Do not be tempted to think of this as \"error handling\"; it\'s not, it\'s just a way to find the place you\'ve *forgotten* to put error handling.\ `set -e`, `set -o errexit`\ proper control flow and error handling `set -e` causes untested non-zero exit statuses to be fatal. It is a debugging feature intended for use only during development and should not be used in production code, especially init scripts and other high-availability scripts. Do not be tempted to think of this as \"error handling\"; it\'s not, it\'s just a way to find the place you\'ve *forgotten* to put error handling.\
and the `ERR` trap Think of it as akin to `use strict` in Perl or `throws` in C++: tough love that makes you write better code. Many guides recommend avoiding it entirely because of the apparently-complex rules for when non-zero statuses cause the script to abort. Conversely, large software projects with experienced coders may recommend or even mandate its use.\ and the `ERR` trap Think of it as akin to `use strict` in Perl or `throws` in C++: tough love that makes you write better code. Many guides recommend avoiding it entirely because of the apparently-complex rules for when non-zero statuses cause the script to abort. Conversely, large software projects with experienced coders may recommend or even mandate its use.\
@ -64,15 +64,15 @@ surprised if you run across someone telling you not to use these.
Syntax Replacement Description Syntax Replacement Description
------------------------------- --------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------- --------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`function\ NAME\ {\ CMDS;\ }` `NAME()\ COMPOUND-CMD` This is the ksh form of function definition created to extend the Bourne and POSIX form with modified behaviors and additional features like local variables. The idea was for new-style functions to be analogous to regular builtins with their own environment and scope, while POSIX-style functions are more like special builtins. `function` is supported by almost every ksh-derived shell including Bash and Zsh, but isn\'t specified by POSIX. Bash treats all function styles the same, but this is unusual. `function` has some preferable characteristics in many ksh variants, making it more portable for scripts that use non-POSIX extensions by some measures. If you\'re going to use the `function` keyword, it implies that you\'re either targeting Ksh specifically, or that you have detailed knowledge of how to compensate for differences across shells. It should always be used consistently with `typeset`, but never used with `declare` or `local`. Also in ksh93, the braces are not a [command group](/syntax/ccmd/grouping_plain), but a required part of the syntax (unlike Bash and others). See [shell function definitions](/syntax/basicgrammar#shell_function_definitions) `function\ NAME\ {\ CMDS;\ }` `NAME()\ COMPOUND-CMD` This is the ksh form of function definition created to extend the Bourne and POSIX form with modified behaviors and additional features like local variables. The idea was for new-style functions to be analogous to regular builtins with their own environment and scope, while POSIX-style functions are more like special builtins. `function` is supported by almost every ksh-derived shell including Bash and Zsh, but isn\'t specified by POSIX. Bash treats all function styles the same, but this is unusual. `function` has some preferable characteristics in many ksh variants, making it more portable for scripts that use non-POSIX extensions by some measures. If you\'re going to use the `function` keyword, it implies that you\'re either targeting Ksh specifically, or that you have detailed knowledge of how to compensate for differences across shells. It should always be used consistently with `typeset`, but never used with `declare` or `local`. Also in ksh93, the braces are not a [command group](../syntax/ccmd/grouping_plain.md), but a required part of the syntax (unlike Bash and others). See [shell function definitions](../syntax/basicgrammar.md#shell_function_definitions)
`typeset` `declare`, `local`, `export`, `readonly` This is closely related to the above, and should often be used together. `typeset` exists primarily for `ksh` compatibility, but is marked as \"deprecated\" in Bash (though I don\'t entirely agree with this). This makes some sense, because future compatibility can\'t be guaranteed, and any compatibility at all, requires understanding the non-POSIX features of other shells and their differences. Using `declare` instead of `typeset` emphasizes your intention to be \"Bash-only\", and definitely breaks everywhere else (except possibly zsh if you\'re lucky). The issue is further complicated by Dash and the [Debian policy](http://www.debian.org/doc/debian-policy/ch-files.html#s-scripts) requirement for a `local` builtin, which is itself not entirely compatible with Bash and other shells. `typeset` `declare`, `local`, `export`, `readonly` This is closely related to the above, and should often be used together. `typeset` exists primarily for `ksh` compatibility, but is marked as \"deprecated\" in Bash (though I don\'t entirely agree with this). This makes some sense, because future compatibility can\'t be guaranteed, and any compatibility at all, requires understanding the non-POSIX features of other shells and their differences. Using `declare` instead of `typeset` emphasizes your intention to be \"Bash-only\", and definitely breaks everywhere else (except possibly zsh if you\'re lucky). The issue is further complicated by Dash and the [Debian policy](http://www.debian.org/doc/debian-policy/ch-files.html#s-scripts) requirement for a `local` builtin, which is itself not entirely compatible with Bash and other shells.
\'\'let \'EXPR\' \'\' `((EXPR))` or `[\ $((EXPR))\ -ne\ 0 ]` `let` is the \"simple command\" variant of arithmetic evaluation command, which takes regular arguments. Both `let` and `((expr))` were present in ksh88, and everything that supports one should support the other. Neither are POSIX. The compound variant is preferable because it doesn\'t take regular arguments for [wordsplitting](/syntax/expansion/wordsplit) and [globbing](/syntax/expansion/globs), which makes it safer and clearer. It is also usually faster, especially in Bash, where compound commands are typically significantly faster. Some of the (few) reasons for using `let` are detailed on the [let](/commands/builtin/let) page. See [arithmetic evaluation compound command](/syntax/ccmd/arithmetic_eval) \'\'let \'EXPR\' \'\' `((EXPR))` or `[\ $((EXPR))\ -ne\ 0 ]` `let` is the \"simple command\" variant of arithmetic evaluation command, which takes regular arguments. Both `let` and `((expr))` were present in ksh88, and everything that supports one should support the other. Neither are POSIX. The compound variant is preferable because it doesn\'t take regular arguments for [wordsplitting](../syntax/expansion/wordsplit.md) and [globbing](../syntax/expansion/globs.md), which makes it safer and clearer. It is also usually faster, especially in Bash, where compound commands are typically significantly faster. Some of the (few) reasons for using `let` are detailed on the [let](../commands/builtin/let.md) page. See [arithmetic evaluation compound command](../syntax/ccmd/arithmetic_eval.md)
`eval` Depends. Often code can be restructured to use better alternatives. `eval` is thrown in here for good measure, as sadly it is so often misused that any use of `eval` (even the rare clever one) is immediately dismissed as wrong by experts, and among the most immediate solutions abused by beginners. In reality, there are correct ways to use `eval`, and even cases in which it\'s necessary, even in sophisticated shells like Bash and Ksh. `eval` is unusual in that it is less frequently appropriate in more feature-rich shells than in more minimal shells like Dash, where it is used to compensate for more limitations. If you find yourself needing `eval` too frequently, it might be a sign that you\'re either better off using a different language entirely, or trying to borrow an idiom from some other paradigm that isn\'t well suited to the shell language. By the same token, there are some cases in which working too hard to avoid `eval` ends up adding a lot of complexity and sacrificing all portability. Don\'t substitute a clever `eval` for something that\'s a bit \"too clever\", just to avoid the `eval`, yet, take reasonable measures to avoid it where it is sensible to do so. See: [eval](/commands/builtin/eval) and [Eval command and security issues](http://mywiki.wooledge.org/BashFAQ/048). `eval` Depends. Often code can be restructured to use better alternatives. `eval` is thrown in here for good measure, as sadly it is so often misused that any use of `eval` (even the rare clever one) is immediately dismissed as wrong by experts, and among the most immediate solutions abused by beginners. In reality, there are correct ways to use `eval`, and even cases in which it\'s necessary, even in sophisticated shells like Bash and Ksh. `eval` is unusual in that it is less frequently appropriate in more feature-rich shells than in more minimal shells like Dash, where it is used to compensate for more limitations. If you find yourself needing `eval` too frequently, it might be a sign that you\'re either better off using a different language entirely, or trying to borrow an idiom from some other paradigm that isn\'t well suited to the shell language. By the same token, there are some cases in which working too hard to avoid `eval` ends up adding a lot of complexity and sacrificing all portability. Don\'t substitute a clever `eval` for something that\'s a bit \"too clever\", just to avoid the `eval`, yet, take reasonable measures to avoid it where it is sensible to do so. See: [eval](../commands/builtin/eval.md) and [Eval command and security issues](http://mywiki.wooledge.org/BashFAQ/048).
## See also ## See also
- [Non-portable syntax and command uses](/scripting/nonportable) - [Non-portable syntax and command uses](../scripting/nonportable.md)
- [bashchanges](/scripting/bashchanges) - [bashchanges](../scripting/bashchanges.md)
- [Greg\'s BashFAQ 061: List of essential features added (with the - [Greg\'s BashFAQ 061: List of essential features added (with the
Bash version tag)](BashFAQ>061) Bash version tag)](BashFAQ>061)
- [Bash \<-\> POSIX Portability guide with a focus on - [Bash \<-\> POSIX Portability guide with a focus on

View File

@ -10,12 +10,12 @@ parameters are described below:
Parameter(s) Description Parameter(s) Description
------------------ ------------------------------------------------------------------------------------------------------------------------------------ ------------------ ------------------------------------------------------------------------------------------------------------------------------------
`$0` the first positional parameter, equivalent to `argv[0]` in C, see [the first argument](/scripting/posparams#the_first_argument) `$0` the first positional parameter, equivalent to `argv[0]` in C, see [the first argument](../scripting/posparams.md#the_first_argument)
`$FUNCNAME` the function name ([**attention**]{.underline}: inside a function, `$0` is still the `$0` of the shell, **not** the function name) `$FUNCNAME` the function name ([**attention**]{.underline}: inside a function, `$0` is still the `$0` of the shell, **not** the function name)
`$1 ... $9` the argument list elements from 1 to 9 `$1 ... $9` the argument list elements from 1 to 9
`${10} ... ${N}` the argument list elements beyond 9 (note the [parameter expansion](/syntax/pe) syntax!) `${10} ... ${N}` the argument list elements beyond 9 (note the [parameter expansion](../syntax/pe.md) syntax!)
`$*` all positional parameters except `$0`, see [mass usage](/scripting/posparams#mass_usage) `$*` all positional parameters except `$0`, see [mass usage](../scripting/posparams.md#mass_usage)
`$@` all positional parameters except `$0`, see [mass usage](/scripting/posparams#mass_usage) `$@` all positional parameters except `$0`, see [mass usage](../scripting/posparams.md#mass_usage)
`$#` the number of arguments, not counting `$0` `$#` the number of arguments, not counting `$0`
These positional parameters reflect exactly what was given to the script These positional parameters reflect exactly what was given to the script
@ -25,7 +25,7 @@ Option-switch parsing (e.g. `-h` for displaying help) is not performed
at this point. at this point.
See also [the dictionary entry for See also [the dictionary entry for
\"parameter\"](/dict/terms/parameter). \"parameter\"](../dict/terms/parameter.md).
## The first argument ## The first argument
@ -105,7 +105,7 @@ There are several ways to loop through the positional parameters.
------------------------------------------------------------------------ ------------------------------------------------------------------------
You can code a [C-style for-loop](/syntax/ccmd/c_for) using `$#` as the You can code a [C-style for-loop](../syntax/ccmd/c_for.md) using `$#` as the
end value. On every iteration, the `shift`-command is used to shift the end value. On every iteration, the `shift`-command is used to shift the
argument list: argument list:
@ -136,7 +136,7 @@ a given wordlist. The loop uses the positional parameters as a wordlist:
The next method is similar to the first example (the `for` loop), but it The next method is similar to the first example (the `for` loop), but it
doesn\'t test for reaching `$#`. It shifts and checks if `$1` still doesn\'t test for reaching `$#`. It shifts and checks if `$1` still
expands to something, using the [test command](/commands/classictest): expands to something, using the [test command](../commands/classictest.md):
while [ "$1" ] while [ "$1" ]
do do
@ -147,7 +147,7 @@ expands to something, using the [test command](/commands/classictest):
Looks nice, but has the disadvantage of stopping when `$1` is empty Looks nice, but has the disadvantage of stopping when `$1` is empty
(null-string). Let\'s modify it to run as long as `$1` is defined (but (null-string). Let\'s modify it to run as long as `$1` is defined (but
may be null), using [parameter expansion for an alternate may be null), using [parameter expansion for an alternate
value](/syntax/pe#use_an_alternate_value): value](../syntax/pe.md#use_an_alternate_value):
while [ "${1+defined}" ]; do while [ "${1+defined}" ]; do
echo "$1" echo "$1"
@ -157,7 +157,7 @@ value](/syntax/pe#use_an_alternate_value):
### Getopts ### Getopts
There is a [small tutorial dedicated to There is a [small tutorial dedicated to
`getopts`](/howto/getopts_tutorial) (*under construction*). `getopts`](../howto/getopts_tutorial.md) (*under construction*).
## Mass usage ## Mass usage
@ -203,8 +203,8 @@ Well, let\'s just say: **You almost always want a quoted `"$@"`!**
Another way to mass expand the positional parameters is similar to what Another way to mass expand the positional parameters is similar to what
is possible for a range of characters using [substring is possible for a range of characters using [substring
expansion](/syntax/pe#substring_expansion) on normal parameters and the expansion](../syntax/pe.md#substring_expansion) on normal parameters and the
mass expansion range of [arrays](/syntax/arrays). mass expansion range of [arrays](../syntax/arrays.md).
`${@:START:COUNT}` `${@:START:COUNT}`
@ -237,7 +237,7 @@ when the positional parameters are in use. A `START` of `1` begins at
## Setting Positional Parameters ## Setting Positional Parameters
Setting positional parameters with command line arguments, is not the Setting positional parameters with command line arguments, is not the
only way to set them. The [builtin command, set](/commands/builtin/set) only way to set them. The [builtin command, set](../commands/builtin/set.md)
may be used to \"artificially\" change the positional parameters from may be used to \"artificially\" change the positional parameters from
inside the script or function: inside the script or function:
@ -382,16 +382,16 @@ options\" for `ls` and doesn\'t change anything after it:
### Using getopts ### Using getopts
There is a [small tutorial dedicated to There is a [small tutorial dedicated to
`getopts`](/howto/getopts_tutorial) (*under construction*). `getopts`](../howto/getopts_tutorial.md) (*under construction*).
## See also ## See also
- Internal: [getopts_tutorial](/howto/getopts_tutorial) - Internal: [getopts_tutorial](../howto/getopts_tutorial.md)
- Internal: [while_loop](/syntax/ccmd/while_loop) - Internal: [while_loop](../syntax/ccmd/while_loop.md)
- Internal: [c_for](/syntax/ccmd/c_for) - Internal: [c_for](../syntax/ccmd/c_for.md)
- Internal: [arrays](/syntax/arrays) (for equivalent syntax for - Internal: [arrays](../syntax/arrays.md) (for equivalent syntax for
mass-expansion) mass-expansion)
- Internal: [Substring expansion on a - Internal: [Substring expansion on a
parameter](/syntax/pe#substring_expansion) (for equivalent syntax parameter](../syntax/pe.md#substring_expansion) (for equivalent syntax
for mass-expansion) for mass-expansion)
- Dictionary, internal: [parameter](/dict/terms/parameter) - Dictionary, internal: [parameter](../dict/terms/parameter.md)

View File

@ -26,8 +26,8 @@ need to put it into the environment with the bash builtin command
export MYVAR export MYVAR
Common system variables like [PATH](/syntax/shellvars#PATH) or Common system variables like [PATH](../syntax/shellvars.md#PATH) or
[HOME](/syntax/shellvars#HOME) are usually part of the environment (as [HOME](../syntax/shellvars.md#HOME) are usually part of the environment (as
set by login scripts or programs). set by login scripts or programs).
## Executing programs ## Executing programs
@ -163,7 +163,7 @@ are run inside a subshell:
### Command substitution ### Command substitution
With [command substitution](/syntax/expansion/cmdsubst) you re-use the With [command substitution](../syntax/expansion/cmdsubst.md) you re-use the
output of another command as text in your command line, for example to output of another command as text in your command line, for example to
set a variable. The other command is run in a subshell: set a variable. The other command is run in a subshell:

View File

@ -33,7 +33,7 @@ many may prefer 4 spaces, see below in the discussion section):
Speaking of hard-tabs: Avoid them if possible. They only make trouble. I Speaking of hard-tabs: Avoid them if possible. They only make trouble. I
can imagine one case where they\'re useful: Indenting can imagine one case where they\'re useful: Indenting
[here-documents](/syntax/redirection#here_documents). [here-documents](../syntax/redirection.md#here_documents).
### Breaking up lines ### Breaking up lines
@ -55,7 +55,7 @@ supports the visual impression of \"these belong together\".
### Breaking compound commands ### Breaking compound commands
[Compound commands](/syntax/ccmd/intro) form the structures that make a [Compound commands](../syntax/ccmd/intro.md) form the structures that make a
shell script different from a stupid enumeration of commands. Usually shell script different from a stupid enumeration of commands. Usually
they contain a kind of \"head\" and a \"body\" that contains command they contain a kind of \"head\" and a \"body\" that contains command
lists. This type of compound command is relatively easy to indent. lists. This type of compound command is relatively easy to indent.
@ -242,7 +242,7 @@ Bash, but is not a good idea.
### Command substitution ### Command substitution
As noted in [the article about command As noted in [the article about command
substitution](/syntax/expansion/cmdsubst), you should use the `$( ... )` substitution](../syntax/expansion/cmdsubst.md), you should use the `$( ... )`
form. form.
If portability is a concern, use the backquoted form `` ` ... ` ``. If portability is a concern, use the backquoted form `` ` ... ` ``.
@ -279,7 +279,7 @@ The basic structure of a script simply reads:
### The shebang ### The shebang
If possible (I know it\'s not always possible!), use [a If possible (I know it\'s not always possible!), use [a
shebang](/dict/terms/shebang). shebang](../dict/terms/shebang.md).
Be careful with `/bin/sh`: The argument that \"on Linux `/bin/sh` is Be careful with `/bin/sh`: The argument that \"on Linux `/bin/sh` is
Bash\" **is a lie** (and technically irrelevant) Bash\" **is a lie** (and technically irrelevant)
@ -314,7 +314,7 @@ have to ensure they\'re in a specific order.
The portable form of the function definition should be used, without the The portable form of the function definition should be used, without the
`function` keyword (here using the [grouping compound `function` keyword (here using the [grouping compound
command](/syntax/ccmd/grouping_plain)): command](../syntax/ccmd/grouping_plain.md)):
getargs() { getargs() {
... ...
@ -358,7 +358,7 @@ Example:
### Exit meaningfully ### Exit meaningfully
The [exit code](/dict/terms/exit_status) is your only way to directly The [exit code](../dict/terms/exit_status.md) is your only way to directly
communicate with the calling process without any special provisions. communicate with the calling process without any special provisions.
If your script exits, provide a meaningful exit code. That minimally If your script exits, provide a meaningful exit code. That minimally
@ -380,7 +380,7 @@ of their C programs.\"** *\-- Robert Firth*
- if the script is interactive, if it works for you and if you think - if the script is interactive, if it works for you and if you think
this is a nice feature, you can try to [save the terminal content this is a nice feature, you can try to [save the terminal content
and restore it](/snipplets/screen_saverestore) after execution and restore it](../snipplets/screen_saverestore.md) after execution
- output clean and understandable screen messages - output clean and understandable screen messages
- if applicable, you can use colors or specific prefixes to tag error - if applicable, you can use colors or specific prefixes to tag error
and warning messages and warning messages

View File

@ -29,7 +29,7 @@ reset the color changes in bash. Like so \....
echo -e "$COL_YELLOW This is yellow $COL_RESET" echo -e "$COL_YELLOW This is yellow $COL_RESET"
But also see the notes in [the article about using But also see the notes in [the article about using
terminalcodes](/scripting/terminalcodes) about generating codes and terminalcodes](../scripting/terminalcodes.md) about generating codes and
hardwiring codes. hardwiring codes.
This snipplet sets up associative arrays for basic color codes using This snipplet sets up associative arrays for basic color codes using

View File

@ -6,7 +6,7 @@ LastUpdate_dt: 2010-07-31 Contributors: Jan Schampera type: snipplet
------------------------------------------------------------------------ ------------------------------------------------------------------------
From the [example section of the read From the [example section of the read
command](/commands/builtin/read#examples), something that acts similar command](../commands/builtin/read.md#examples), something that acts similar
to the MSDOS `pause` command: to the MSDOS `pause` command:
pause() { pause() {

View File

@ -13,7 +13,7 @@ Check this script (save it as script file or make a function):
printf '"%b"\n' "$0" "$@" | nl -v0 -s": " printf '"%b"\n' "$0" "$@" | nl -v0 -s": "
It uses the [printf command](/commands/builtin/printf) to generate a It uses the [printf command](../commands/builtin/printf.md) to generate a
list of arguments, even with escape sequences interpreted. This list is list of arguments, even with escape sequences interpreted. This list is
shown formatted by the nl(1) utility. shown formatted by the nl(1) utility.

View File

@ -78,7 +78,7 @@ naturally, invisible. What you see is the dash, repeated 20 times.
printf '%.0s-' {1..20}; echo printf '%.0s-' {1..20}; echo
``` ```
If the 20 is variable, you can use [eval](/commands/builtin/eval) to If the 20 is variable, you can use [eval](../commands/builtin/eval.md) to
insert the expansion (take care that using `eval` is potentially insert the expansion (take care that using `eval` is potentially
dangerous if you evaluate external data): dangerous if you evaluate external data):
@ -95,7 +95,7 @@ eval printf %.1s '-{1..'"${COLUMNS:-$(tput cols)}"\}; echo
You can also do it the crazy ormaaj way™ following basically the same You can also do it the crazy ormaaj way™ following basically the same
principle as this [string reverse principle as this [string reverse
example](/commands/builtin/eval#expansion_side-effects). It completely example](../commands/builtin/eval.md#expansion_side-effects). It completely
depends on Bash due to its brace expansion evaluation order and array depends on Bash due to its brace expansion evaluation order and array
parameter parsing details. As above, the eval only inserts the COLUMNS parameter parsing details. As above, the eval only inserts the COLUMNS
expansion into the expression and isn\'t involved in the rest, other expansion into the expression and isn\'t involved in the rest, other
@ -132,4 +132,4 @@ hr() {
## Related articles ## Related articles
- [printf](/commands/builtin/printf) - [printf](../commands/builtin/printf.md)

View File

@ -67,11 +67,11 @@ rndstr()
The remaining examples don\'t use quite the same tricks, which will The remaining examples don\'t use quite the same tricks, which will
hopefully be explained elsewhere eventually. See hopefully be explained elsewhere eventually. See
[unset](commands/builtin/unset#scope) for why doing assignments in this [unset](../commands/builtin/unset.md#scope) for why doing assignments in this
way works well. way works well.
This next example is a variation on This next example is a variation on
[print_horizontal_line](/snipplets/print_horizontal_line). We\'re using [print_horizontal_line](../snipplets/print_horizontal_line.md). We\'re using
the printf field width specifier to truncate the values of a the printf field width specifier to truncate the values of a
`sequence expansion` to one character. `sequence expansion` to one character.
@ -81,12 +81,12 @@ printf '%.1s' "${a[RANDOM%${#a[@]}]}"{0..9} $'\n'
``` ```
The extra detail that makes this work is to notice that in Bash, [brace The extra detail that makes this work is to notice that in Bash, [brace
expansion](syntax/expansion/brace) is usually the very first type of expansion](../syntax/expansion/brace.md) is usually the very first type of
expansion to be processed, always before parameter expansion. Bash is expansion to be processed, always before parameter expansion. Bash is
unique in this respect \-- all other shells with a brace expansion unique in this respect \-- all other shells with a brace expansion
feature perform it almost last, just before pathname expansion. First feature perform it almost last, just before pathname expansion. First
the sequence expansion generates ten parameters, then the parameters are the sequence expansion generates ten parameters, then the parameters are
expanded left-to-right causing the [arithmetic](/syntax/arith_expr) for expanded left-to-right causing the [arithmetic](../syntax/arith_expr.md) for
each to be evaluated individually, resulting in independent selection of each to be evaluated individually, resulting in independent selection of
random element of `a`. To get ten of the same element, put the array random element of `a`. To get ten of the same element, put the array
selection inside the format string where it will only be evaluated once, selection inside the format string where it will only be evaluated once,

View File

@ -40,7 +40,7 @@ There are two (maybe more) easy options:
- writing out singlequoted strings and handle the embedded - writing out singlequoted strings and handle the embedded
singlequotes singlequotes
- the [printf command](/commands/builtin/printf) knows the `%q` format - the [printf command](../commands/builtin/printf.md) knows the `%q` format
specification, which will print a string (like `%s` does), but with specification, which will print a string (like `%s` does), but with
all shell special characters escaped all shell special characters escaped

View File

@ -4,13 +4,13 @@
Arithmetic expressions are used in several situations: Arithmetic expressions are used in several situations:
- [arithmetic evaluation command](/syntax/ccmd/arithmetic_eval) - [arithmetic evaluation command](../syntax/ccmd/arithmetic_eval.md)
- [arithmetic expansion](/syntax/expansion/arith) - [arithmetic expansion](../syntax/expansion/arith.md)
- [substring parameter expansion](/syntax/pe#substring_expansion) - [substring parameter expansion](../syntax/pe.md#substring_expansion)
- [the `let` builtin command](/commands/builtin/let) - [the `let` builtin command](../commands/builtin/let.md)
- [C-style for loop](/syntax/ccmd/c_for) - [C-style for loop](../syntax/ccmd/c_for.md)
- [array indexing](/syntax/arrays) - [array indexing](../syntax/arrays.md)
- [conditional expressions](/syntax/ccmd/conditional_expression) - [conditional expressions](../syntax/ccmd/conditional_expression.md)
- Assignment statements, and arguments to declaration commands of - Assignment statements, and arguments to declaration commands of
variables with the integer attribute. variables with the integer attribute.
@ -95,7 +95,7 @@ and what numbers are and how they are built, then you don\'t need
different bases. different bases.
If you want to convert between the usual bases (octal, decimal, hex), If you want to convert between the usual bases (octal, decimal, hex),
use [the printf command](/commands/builtin/printf) and its format use [the printf command](../commands/builtin/printf.md) and its format
strings. strings.
## Shell variables ## Shell variables
@ -121,7 +121,7 @@ When variables are referenced, the notation `1 + $X` is equivalent to
the notation `1 + X`, both are allowed. the notation `1 + X`, both are allowed.
When variables are referenced like `$X`, the rules of [parameter When variables are referenced like `$X`, the rules of [parameter
expansion](/syntax/pe) apply and are performed **before** the expression expansion](../syntax/pe.md) apply and are performed **before** the expression
is evaluated. Thus, a construct like `${MYSTRING:4:3}` is valid inside is evaluated. Thus, a construct like `${MYSTRING:4:3}` is valid inside
an arithmetic expression. an arithmetic expression.
@ -130,7 +130,7 @@ an arithmetic expression.
Unlike command exit and return codes, arithmetic expressions evaluate to Unlike command exit and return codes, arithmetic expressions evaluate to
logical \"true\" when they are not 0. When they are 0, they evaluate to logical \"true\" when they are not 0. When they are 0, they evaluate to
\"false\". The [arithmetic evaluation compound \"false\". The [arithmetic evaluation compound
command](/syntax/ccmd/arithmetic_eval) reverses the \"truth\" of an command](../syntax/ccmd/arithmetic_eval.md) reverses the \"truth\" of an
arithmetic expression to match the \"truth\" of command exit codes: arithmetic expression to match the \"truth\" of command exit codes:
- if the arithmetic expression brings up a value not 0 (arithmetic - if the arithmetic expression brings up a value not 0 (arithmetic
@ -153,16 +153,16 @@ That means, the following `if`-clause will execute the `else`-thread:
Operator Description Operator Description
--------------------- ---------------------------------------------------------------------------------------------------- --------------------- ----------------------------------------------------------------------------------------------------
`<ID> = <EXPR>` normal assignment `<ID> = <EXPR>` normal assignment
`<ID> *= <EXPR>` equivalent to `<ID> = <ID> * <EXPR>`, see [calculation operators](/syntax/arith_expr#calculations) `<ID> *= <EXPR>` equivalent to `<ID> = <ID> * <EXPR>`, see [calculation operators](../syntax/arith_expr.md#calculations)
`<ID> /= <EXPR>` equivalent to `<ID> = <ID> / <EXPR>`, see [calculation operators](/syntax/arith_expr#calculations) `<ID> /= <EXPR>` equivalent to `<ID> = <ID> / <EXPR>`, see [calculation operators](../syntax/arith_expr.md#calculations)
`<ID> %= <EXPR>` equivalent to `<ID> = <ID> % <EXPR>`, see [calculation operators](/syntax/arith_expr#calculations) `<ID> %= <EXPR>` equivalent to `<ID> = <ID> % <EXPR>`, see [calculation operators](../syntax/arith_expr.md#calculations)
`<ID> += <EXPR>` equivalent to `<ID> = <ID> + <EXPR>`, see [calculation operators](/syntax/arith_expr#calculations) `<ID> += <EXPR>` equivalent to `<ID> = <ID> + <EXPR>`, see [calculation operators](../syntax/arith_expr.md#calculations)
`<ID> -= <EXPR>` equivalent to `<ID> = <ID> - <EXPR>`, see [calculation operators](/syntax/arith_expr#calculations) `<ID> -= <EXPR>` equivalent to `<ID> = <ID> - <EXPR>`, see [calculation operators](../syntax/arith_expr.md#calculations)
`<ID> <<= <NUMBER>` equivalent to `<ID> = <ID> << <NUMBER>`, see [bit operations](/syntax/arith_expr#bit_operations) `<ID> <<= <NUMBER>` equivalent to `<ID> = <ID> << <NUMBER>`, see [bit operations](../syntax/arith_expr.md#bit_operations)
`<ID> >>= <NUMBER>` equivalent to `<ID> = <ID> >> <NUMBER>`, see [bit operations](/syntax/arith_expr#bit_operations) `<ID> >>= <NUMBER>` equivalent to `<ID> = <ID> >> <NUMBER>`, see [bit operations](../syntax/arith_expr.md#bit_operations)
`<ID> &= <EXPR>` equivalent to `<ID> = <ID> & <EXPR>`, see [bit operations](/syntax/arith_expr#bit_operations) `<ID> &= <EXPR>` equivalent to `<ID> = <ID> & <EXPR>`, see [bit operations](../syntax/arith_expr.md#bit_operations)
`<ID> ^= <EXPR>` equivalent to `<ID> = <ID> ^ <EXPR>`, see [bit operations](/syntax/arith_expr#bit_operations) `<ID> ^= <EXPR>` equivalent to `<ID> = <ID> ^ <EXPR>`, see [bit operations](../syntax/arith_expr.md#bit_operations)
`<ID> |= <EXPR>` equivalent to `<ID> = <ID> | <EXPR>`, see [bit operations](/syntax/arith_expr#bit_operations) `<ID> |= <EXPR>` equivalent to `<ID> = <ID> | <EXPR>`, see [bit operations](../syntax/arith_expr.md#bit_operations)
### Calculations ### Calculations
@ -336,8 +336,8 @@ under set -e. \</WRAP\>
## Arithmetic expressions in Bash ## Arithmetic expressions in Bash
- [The C-style for-loop](/syntax/ccmd/c_for) - [The C-style for-loop](../syntax/ccmd/c_for.md)
- [Arithmetic expansion](/syntax/expansion/arith) - [Arithmetic expansion](../syntax/expansion/arith.md)
- [Arithmetic evaluation compound - [Arithmetic evaluation compound
command](/syntax/ccmd/arithmetic_eval) command](../syntax/ccmd/arithmetic_eval.md)
- [The \"let\" builtin command](/commands/builtin/let) - [The \"let\" builtin command](../commands/builtin/let.md)

View File

@ -31,7 +31,7 @@ Bash supports two different types of ksh-like one-dimensional arrays.
arrays are **always sparse**, meaning indexes are not necessarily arrays are **always sparse**, meaning indexes are not necessarily
contiguous. All syntax used for both assigning and dereferencing contiguous. All syntax used for both assigning and dereferencing
indexed arrays is an [arithmetic evaluation indexed arrays is an [arithmetic evaluation
context](/syntax/arith_expr) (see [#Referencing](#Referencing)). As context](../syntax/arith_expr.md) (see [#Referencing](#Referencing)). As
in C and many other languages, the numerical array indexes start at in C and many other languages, the numerical array indexes start at
0 (zero). Indexed arrays are the most common, useful, and portable 0 (zero). Indexed arrays are the most common, useful, and portable
type. Indexed arrays were first introduced to Bourne-like shells by type. Indexed arrays were first introduced to Bourne-like shells by
@ -69,7 +69,7 @@ The overall syntax is `arrname[subscript]` - where for indexed arrays,
arrays, any nonempty string. Subscripts are first processed for arrays, any nonempty string. Subscripts are first processed for
parameter and arithmetic expansions, and command and process parameter and arithmetic expansions, and command and process
substitutions. When used within parameter expansions or as an argument substitutions. When used within parameter expansions or as an argument
to the [unset](commands/builtin/unset) builtin, the special subscripts to the [unset](../commands/builtin/unset.md) builtin, the special subscripts
`*` and `@` are also accepted which act upon arrays analogously to the `*` and `@` are also accepted which act upon arrays analogously to the
way the `@` and `*` special parameters act upon the positional way the `@` and `*` special parameters act upon the positional
parameters. In parsing the subscript, bash ignores any text that follows parameters. In parsing the subscript, bash ignores any text that follows
@ -77,7 +77,7 @@ the closing bracket up to the end of the parameter name.
With few exceptions, names of this form may be used anywhere ordinary With few exceptions, names of this form may be used anywhere ordinary
parameter names are valid, such as within [arithmetic parameter names are valid, such as within [arithmetic
expressions](/syntax/arith_expr), [parameter expansions](/syntax/pe), expressions](../syntax/arith_expr.md), [parameter expansions](../syntax/pe.md),
and as arguments to builtins that accept parameter names. An *array* is and as arguments to builtins that accept parameter names. An *array* is
a Bash parameter that has been given the `-a` (for indexed) or `-A` (for a Bash parameter that has been given the `-a` (for indexed) or `-A` (for
associative) *attributes*. However, any regular (non-special or associative) *attributes*. However, any regular (non-special or
@ -118,7 +118,7 @@ variables.
Syntax Description Syntax Description
--------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`ARRAY[N]=VALUE` Sets the element `N` of the **indexed** array `ARRAY` to `VALUE`. **`N` can be any valid [arithmetic expression](/syntax/arith_expr)**. `ARRAY[N]=VALUE` Sets the element `N` of the **indexed** array `ARRAY` to `VALUE`. **`N` can be any valid [arithmetic expression](../syntax/arith_expr.md)**.
`ARRAY[STRING]=VALUE` Sets the element indexed by `STRING` of the **associative array** `ARRAY`. `ARRAY[STRING]=VALUE` Sets the element indexed by `STRING` of the **associative array** `ARRAY`.
`ARRAY=VALUE` As above. If no index is given, as a default the zeroth element is set to `VALUE`. Careful, this is even true of associative arrays - there is no error if no key is specified, and the value is assigned to string index \"0\". `ARRAY=VALUE` As above. If no index is given, as a default the zeroth element is set to `VALUE`. Careful, this is even true of associative arrays - there is no error if no key is specified, and the value is assigned to string index \"0\".
`ARRAY=(E1\ E2\ ...)` Compound array assignment - sets the whole array `ARRAY` to the given list of elements indexed sequentially starting at zero. The array is unset before assignment unless the += operator is used. When the list is empty (`ARRAY=()`), the array will be set to an empty array. This method obviously does not use explicit indexes. An **associative array** can **not** be set like that! Clearing an associative array using `ARRAY=()` works. `ARRAY=(E1\ E2\ ...)` Compound array assignment - sets the whole array `ARRAY` to the given list of elements indexed sequentially starting at zero. The array is unset before assignment unless the += operator is used. When the list is empty (`ARRAY=()`), the array will be set to an empty array. This method obviously does not use explicit indexes. An **associative array** can **not** be set like that! Clearing an associative array using `ARRAY=()` works.
@ -132,20 +132,20 @@ As of now, arrays can\'t be exported.
### Getting values ### Getting values
\<note\> For completeness and details on several parameter expansion \<note\> For completeness and details on several parameter expansion
variants, see the [article about parameter expansion](/syntax/pe) and variants, see the [article about parameter expansion](../syntax/pe.md) and
check the notes about arrays. \</note\> check the notes about arrays. \</note\>
Syntax Description Syntax Description
----------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`${ARRAY[N]}` Expands to the value of the index `N` in the **indexed** array `ARRAY`. If `N` is a negative number, it\'s treated as the offset from the maximum assigned index (can\'t be used for assignment) - 1 `${ARRAY[N]}` Expands to the value of the index `N` in the **indexed** array `ARRAY`. If `N` is a negative number, it\'s treated as the offset from the maximum assigned index (can\'t be used for assignment) - 1
`${ARRAY[S]}` Expands to the value of the index `S` in the **associative** array `ARRAY`. `${ARRAY[S]}` Expands to the value of the index `S` in the **associative** array `ARRAY`.
`"${ARRAY[@]}" ${ARRAY[@]} "${ARRAY[*]}" ${ARRAY[*]}` Similar to [mass-expanding positional parameters](/scripting/posparams#mass_usage), this expands to all elements. If unquoted, both subscripts `*` and `@` expand to the same result, if quoted, `@` expands to all elements individually quoted, `*` expands to all elements quoted as a whole. `"${ARRAY[@]}" ${ARRAY[@]} "${ARRAY[*]}" ${ARRAY[*]}` Similar to [mass-expanding positional parameters](../scripting/posparams.md#mass_usage), this expands to all elements. If unquoted, both subscripts `*` and `@` expand to the same result, if quoted, `@` expands to all elements individually quoted, `*` expands to all elements quoted as a whole.
`"${ARRAY[@]:N:M}" ${ARRAY[@]:N:M} "${ARRAY[*]:N:M}" ${ARRAY[*]:N:M}` Similar to what this syntax does for the characters of a single string when doing [substring expansion](/syntax/pe#substring_expansion), this expands to `M` elements starting with element `N`. This way you can mass-expand individual indexes. The rules for quoting and the subscripts `*` and `@` are the same as above for the other mass-expansions. `"${ARRAY[@]:N:M}" ${ARRAY[@]:N:M} "${ARRAY[*]:N:M}" ${ARRAY[*]:N:M}` Similar to what this syntax does for the characters of a single string when doing [substring expansion](../syntax/pe.md#substring_expansion), this expands to `M` elements starting with element `N`. This way you can mass-expand individual indexes. The rules for quoting and the subscripts `*` and `@` are the same as above for the other mass-expansions.
For clarification: When you use the subscripts `@` or `*` for For clarification: When you use the subscripts `@` or `*` for
mass-expanding, then the behaviour is exactly what it is for `$@` and mass-expanding, then the behaviour is exactly what it is for `$@` and
`$*` when [mass-expanding the positional `$*` when [mass-expanding the positional
parameters](/scripting/posparams#mass_usage). You should read this parameters](../scripting/posparams.md#mass_usage). You should read this
article to understand what\'s going on. article to understand what\'s going on.
### Metadata ### Metadata
@ -166,7 +166,7 @@ article to understand what\'s going on.
### Destruction ### Destruction
The [unset](commands/builtin/unset) builtin command is used to destroy The [unset](../commands/builtin/unset.md) builtin command is used to destroy
(unset) arrays or individual elements of arrays. (unset) arrays or individual elements of arrays.
-------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------
@ -182,12 +182,12 @@ The [unset](commands/builtin/unset) builtin command is used to destroy
-------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------
It is best to [explicitly specify It is best to [explicitly specify
-v](commands/builtin/unset#portability_considerations) when unsetting -v](../commands/builtin/unset.md#portability_considerations) when unsetting
variables with unset. variables with unset.
\<note warning\> Specifying unquoted array elements as arguments to any \<note warning\> Specifying unquoted array elements as arguments to any
command, such as with the syntax above **may cause [pathname command, such as with the syntax above **may cause [pathname
expansion](/syntax/expansion/globs) to occur** due to the presence of expansion](../syntax/expansion/globs.md) to occur** due to the presence of
glob characters. glob characters.
Example: You are in a directory with a file named `x1`, and you want to Example: You are in a directory with a file named `x1`, and you want to
@ -678,10 +678,10 @@ to generate these results.
## See also ## See also
- [Parameter expansion](/syntax/pe) (contains sections for arrays) - [Parameter expansion](../syntax/pe.md) (contains sections for arrays)
- [classic_for](/syntax/ccmd/classic_for) (contains some examples to - [classic_for](../syntax/ccmd/classic_for.md) (contains some examples to
iterate over arrays) iterate over arrays)
- [declare](/commands/builtin/declare) - [declare](../commands/builtin/declare.md)
- [BashFAQ 005 - How can I use array - [BashFAQ 005 - How can I use array
variables?](http://mywiki.wooledge.org/BashFAQ/005) - A very variables?](http://mywiki.wooledge.org/BashFAQ/005) - A very
detailed discussion on arrays with many examples. detailed discussion on arrays with many examples.

View File

@ -42,7 +42,7 @@ issue to report back to the calling program.
**base** for all higher constructs. Everything you execute, from **base** for all higher constructs. Everything you execute, from
pipelines to functions, finally ends up in (many) simple commands. pipelines to functions, finally ends up in (many) simple commands.
That\'s why Bash only has one method to [expand and execute a simple That\'s why Bash only has one method to [expand and execute a simple
command](/syntax/grammar/parser_exec). \</wrap\> command](../syntax/grammar/parser_exec.md). \</wrap\>
## Pipelines ## Pipelines
@ -82,7 +82,7 @@ acts on) exit code 0 (TRUE) and the `then` part of the `if` stanza is
executed. One could say we checked for executed. One could say we checked for
\"`not grep "^root" /etc/passwd`\". \"`not grep "^root" /etc/passwd`\".
The [set option pipefail](/commands/builtin/set#attributes) determines The [set option pipefail](../commands/builtin/set.md#attributes) determines
the behavior of how bash reports the exit code of a pipeline. If it\'s the behavior of how bash reports the exit code of a pipeline. If it\'s
set, then the exit code (`$?`) is the last command that exits with non set, then the exit code (`$?`) is the last command that exits with non
zero status, if none fail, it\'s zero. If it\'s not set, then `$?` zero status, if none fail, it\'s zero. If it\'s not set, then `$?`
@ -111,7 +111,7 @@ syntax:
FIXME Missing an additional article about list operators FIXME Missing an additional article about list operators
A list is a sequence of one or more [pipelines](basicgrammar#pipelines) A list is a sequence of one or more [pipelines](../basicgrammar.md#pipelines)
separated by one of the operators `;`, `&`, `&&`, or `││`, and separated by one of the operators `;`, `&`, `&&`, or `││`, and
optionally terminated by one of `;`, `&`, or `<newline>`. optionally terminated by one of `;`, `&`, or `<newline>`.
@ -132,7 +132,7 @@ Your whole Bash script technically is one big single list!
## Compound Commands ## Compound Commands
See also the [list of compound commands](/syntax/ccmd/intro). See also the [list of compound commands](../syntax/ccmd/intro.md).
There are two forms of compound commands: There are two forms of compound commands:
@ -151,24 +151,24 @@ overview):
Compound command syntax Description Compound command syntax Description
------------------------------------------------------------ --------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------ ---------------------------------------------------------------------------------------------------------------------------------------------------------
`( <LIST> )` Execute `<LIST>` in an extra subshell =\> [article](/syntax/ccmd/grouping_subshell) `( <LIST> )` Execute `<LIST>` in an extra subshell =\> [article](../syntax/ccmd/grouping_subshell.md)
`{ <LIST> ; }` Execute `<LIST>` as separate group (but not in a subshell) =\> [article](/syntax/ccmd/grouping_plain) `{ <LIST> ; }` Execute `<LIST>` as separate group (but not in a subshell) =\> [article](../syntax/ccmd/grouping_plain.md)
`(( <EXPRESSION> ))` Evaluate the arithmetic expression `<EXPRESSION>` =\> [article](/syntax/ccmd/arithmetic_eval) `(( <EXPRESSION> ))` Evaluate the arithmetic expression `<EXPRESSION>` =\> [article](../syntax/ccmd/arithmetic_eval.md)
`[[ <EXPRESSION> ]]` Evaluate the conditional expression `<EXPRESSION>` (aka \"the new test command\") =\> [article](/syntax/ccmd/conditional_expression) `[[ <EXPRESSION> ]]` Evaluate the conditional expression `<EXPRESSION>` (aka \"the new test command\") =\> [article](../syntax/ccmd/conditional_expression.md)
`for <NAME> in <WORDS> ; do <LIST> ; done` Executes `<LIST>` while setting the variable `<NAME>` to one of `<WORDS>` on every iteration (classic for-loop) =\> [article](/syntax/ccmd/classic_for) `for <NAME> in <WORDS> ; do <LIST> ; done` Executes `<LIST>` while setting the variable `<NAME>` to one of `<WORDS>` on every iteration (classic for-loop) =\> [article](../syntax/ccmd/classic_for.md)
`for (( <EXPR1> ; <EXPR2> ; <EXPR3> )) ; do <LIST> ; done` C-style for-loop (driven by arithmetic expressions) =\> [article](/syntax/ccmd/c_for) `for (( <EXPR1> ; <EXPR2> ; <EXPR3> )) ; do <LIST> ; done` C-style for-loop (driven by arithmetic expressions) =\> [article](../syntax/ccmd/c_for.md)
`select <NAME> in <WORDS> ; do <LIST> ; done` Provides simple menus =\> [article](/syntax/ccmd/user_select) `select <NAME> in <WORDS> ; do <LIST> ; done` Provides simple menus =\> [article](../syntax/ccmd/user_select.md)
`case <WORD> in <PATTERN>) <LIST> ;; ... esac` Decisions based on pattern matching - executing `<LIST>` on match =\> [article](/syntax/ccmd/case) `case <WORD> in <PATTERN>) <LIST> ;; ... esac` Decisions based on pattern matching - executing `<LIST>` on match =\> [article](../syntax/ccmd/case.md)
`if <LIST> ; then <LIST> ; else <LIST> ; fi` The if clause: makes decisions based on exit codes =\> [article](/syntax/ccmd/if_clause) `if <LIST> ; then <LIST> ; else <LIST> ; fi` The if clause: makes decisions based on exit codes =\> [article](../syntax/ccmd/if_clause.md)
`while <LIST1> ; do <LIST2> ; done` Execute `<LIST2>` while `<LIST1>` returns TRUE (exit code) =\> [article](/syntax/ccmd/while_loop) `while <LIST1> ; do <LIST2> ; done` Execute `<LIST2>` while `<LIST1>` returns TRUE (exit code) =\> [article](../syntax/ccmd/while_loop.md)
`until <LIST1> ; do <LIST2> ; done` Execute `<LIST2>` until `<LIST1>` returns TRUE (exit code) =\> [article](/syntax/ccmd/until_loop) `until <LIST1> ; do <LIST2> ; done` Execute `<LIST2>` until `<LIST1>` returns TRUE (exit code) =\> [article](../syntax/ccmd/until_loop.md)
## Shell Function Definitions ## Shell Function Definitions
FIXME Missing an additional article about shell functions FIXME Missing an additional article about shell functions
A shell function definition makes a [compound A shell function definition makes a [compound
command](basicgrammar#compound_commands) available via a new name. When command](../basicgrammar.md#compound_commands) available via a new name. When
the function runs, it has its own \"private\" set of positional the function runs, it has its own \"private\" set of positional
parameters and I/O descriptors. It acts like a script-within-the-script. parameters and I/O descriptors. It acts like a script-within-the-script.
Simply stated: **You\'ve created a new command.** Simply stated: **You\'ve created a new command.**
@ -183,7 +183,7 @@ looks like:
print_help() { echo "Sorry, no help available"; } print_help() { echo "Sorry, no help available"; }
As above, a function definition can have any [compound As above, a function definition can have any [compound
command](basicgrammar#compound_commands) as a body. Structures like command](../basicgrammar.md#compound_commands) as a body. Structures like
countme() for ((x=1;x<=9;x++)); do echo $x; done countme() for ((x=1;x<=9;x++)); do echo $x; done
@ -265,17 +265,17 @@ Weird function names should not be used. Quote from the maintainer:
## Grammar summary ## Grammar summary
- a [simple command](basicgrammar#simple_commands) is just a command - a [simple command](../basicgrammar.md#simple_commands) is just a command
and its arguments and its arguments
- a [pipeline](basicgrammar#pipelines) is one or more [simple - a [pipeline](../basicgrammar.md#pipelines) is one or more [simple
command](basicgrammar#simple_commands) probably connected in a pipe command](../basicgrammar.md#simple_commands) probably connected in a pipe
- a [list](basicgrammar#lists) is one or more - a [list](../basicgrammar.md#lists) is one or more
[pipelines](basicgrammar#pipelines) connected by special operators [pipelines](../basicgrammar.md#pipelines) connected by special operators
- a [compound command](basicgrammar#compound_commands) is a - a [compound command](../basicgrammar.md#compound_commands) is a
[list](basicgrammar#lists) or a special command that forms a new [list](../basicgrammar.md#lists) or a special command that forms a new
meta-command meta-command
- a [function definition](basicgrammar#shell_function_definitions) - a [function definition](../basicgrammar.md#shell_function_definitions)
makes a [compound command](basicgrammar#compound_commands) available makes a [compound command](../basicgrammar.md#compound_commands) available
under a new name, and a separate environment under a new name, and a separate environment
## Examples for classification ## Examples for classification
@ -304,12 +304,12 @@ FIXME more\...
cp mymusic.mp3 /data/mp3 cp mymusic.mp3 /data/mp3
fi fi
- the [compound command](basicgrammar#compound_commands) for the `if` - the [compound command](../basicgrammar.md#compound_commands) for the `if`
clause clause
- the [list](basicgrammar#lists) that `if` **checks** actually - the [list](../basicgrammar.md#lists) that `if` **checks** actually
contains the [simple command](basicgrammar#simple_commands) contains the [simple command](../basicgrammar.md#simple_commands)
`[ -d /data/mp3 ]` `[ -d /data/mp3 ]`
- the [list](basicgrammar#lists) that `if` **executes** contains a - the [list](../basicgrammar.md#lists) that `if` **executes** contains a
simple command (`cp mymusic.mp3 /data/mp3`) simple command (`cp mymusic.mp3 /data/mp3`)
Let\'s invert test command exit code, only one thing changes: Let\'s invert test command exit code, only one thing changes:
@ -318,15 +318,15 @@ Let\'s invert test command exit code, only one thing changes:
cp mymusic.mp3 /data/mp3 cp mymusic.mp3 /data/mp3
fi fi
- the [list](basicgrammar#lists) that `if` **checks** contains a - the [list](../basicgrammar.md#lists) that `if` **checks** contains a
[pipeline](basicgrammar#pipelines) now (because of the `!`) [pipeline](../basicgrammar.md#pipelines) now (because of the `!`)
## See also ## See also
- Internal: [List of compound commands](/syntax/ccmd/intro) - Internal: [List of compound commands](../syntax/ccmd/intro.md)
- Internal: [Parsing and execution of simple - Internal: [Parsing and execution of simple
commands](/syntax/grammar/parser_exec) commands](../syntax/grammar/parser_exec.md)
- Internal: [Quoting and escaping](/syntax/quoting) - Internal: [Quoting and escaping](../syntax/quoting.md)
- Internal: [Introduction to expansions and - Internal: [Introduction to expansions and
substitutions](/syntax/expansion/intro) substitutions](../syntax/expansion/intro.md)
- Internal: [Some words about words\...](/syntax/words) - Internal: [Some words about words\...](../syntax/words.md)

View File

@ -4,14 +4,14 @@
A pattern is a **string description**. Bash uses them in various ways: A pattern is a **string description**. Bash uses them in various ways:
- [Pathname expansion](/syntax/expansion/globs) (Globbing - matching - [Pathname expansion](../syntax/expansion/globs.md) (Globbing - matching
filenames) filenames)
- Pattern matching in [conditional - Pattern matching in [conditional
expressions](/syntax/ccmd/conditional_expression) expressions](../syntax/ccmd/conditional_expression.md)
- [Substring removal](/syntax/pe#substring_removal) and [search and - [Substring removal](../syntax/pe.md#substring_removal) and [search and
replace](/syntax/pe#search_and_replace) in [Parameter replace](../syntax/pe.md#search_and_replace) in [Parameter
Expansion](/syntax/pe) Expansion](../syntax/pe.md)
- Pattern-based branching using the [case command](/syntax/ccmd/case) - Pattern-based branching using the [case command](../syntax/ccmd/case.md)
The pattern description language is relatively easy. Any character The pattern description language is relatively easy. Any character
that\'s not mentioned below matches itself. The `NUL` character may not that\'s not mentioned below matches itself. The `NUL` character may not
@ -75,7 +75,7 @@ Some simple examples using normal pattern matching:
## Extended pattern language ## Extended pattern language
If you set the [shell option](/internals/shell_options) `extglob`, Bash If you set the [shell option](../internals/shell_options.md) `extglob`, Bash
understands some powerful patterns. A `<PATTERN-LIST>` is one or more understands some powerful patterns. A `<PATTERN-LIST>` is one or more
patterns, separated by the pipe-symbol (`PATTERN|PATTERN`). patterns, separated by the pipe-symbol (`PATTERN|PATTERN`).
@ -99,13 +99,13 @@ patterns, separated by the pipe-symbol (`PATTERN|PATTERN`).
option classification description option classification description
------------------- ------------------------------------- ------------------------------------------------------------------------------- ------------------- ------------------------------------- -------------------------------------------------------------------------------
`dotglob` [globbing](/syntax/expansion/globs) see [Pathname expansion customization](/syntax/expansion/globs#Customization) `dotglob` [globbing](../syntax/expansion/globs.md) see [Pathname expansion customization](../syntax/expansion/globs.md#Customization)
`extglob` global enable/disable extended pattern matching language, as described above `extglob` global enable/disable extended pattern matching language, as described above
`failglob` [globbing](/syntax/expansion/globs) see [Pathname expansion customization](/syntax/expansion/globs#Customization) `failglob` [globbing](../syntax/expansion/globs.md) see [Pathname expansion customization](../syntax/expansion/globs.md#Customization)
`nocaseglob` [globbing](/syntax/expansion/globs) see [Pathname expansion customization](/syntax/expansion/globs#Customization) `nocaseglob` [globbing](../syntax/expansion/globs.md) see [Pathname expansion customization](../syntax/expansion/globs.md#Customization)
`nocasematch` pattern/string matching perform pattern matching without regarding the case of individual letters `nocasematch` pattern/string matching perform pattern matching without regarding the case of individual letters
`nullglob` [globbing](/syntax/expansion/globs) see [Pathname expansion customization](/syntax/expansion/globs#Customization) `nullglob` [globbing](../syntax/expansion/globs.md) see [Pathname expansion customization](../syntax/expansion/globs.md#Customization)
`globasciiranges` [globbing](/syntax/expansion/globs) see [Pathname expansion customization](/syntax/expansion/globs#Customization) `globasciiranges` [globbing](../syntax/expansion/globs.md) see [Pathname expansion customization](../syntax/expansion/globs.md#Customization)
## Bugs and Portability considerations ## Bugs and Portability considerations
@ -155,7 +155,7 @@ double extglob negation. The aforementioned ksh93 pattern is equivalent
in Bash to: `[[ fo0bar == !(!(fo[0-9])|!(+([[:alnum:]])))bar ]]`, which in Bash to: `[[ fo0bar == !(!(fo[0-9])|!(+([[:alnum:]])))bar ]]`, which
is technically more portable, but ugly. is technically more portable, but ugly.
\* ksh93\'s [printf](commands/builtin/printf) builtin can translate from \* ksh93\'s [printf](../commands/builtin/printf.md) builtin can translate from
shell patterns to ERE and back again using the `%R` and `%P` format shell patterns to ERE and back again using the `%R` and `%P` format
specifiers respectively. specifiers respectively.

View File

@ -9,7 +9,7 @@ is an entity that stores values and is referenced by a **name**, a
**number** or a **special symbol**. **number** or a **special symbol**.
- parameters referenced by a name are called **variables** (this also - parameters referenced by a name are called **variables** (this also
applies to [arrays](/syntax/arrays)) applies to [arrays](../syntax/arrays.md))
- parameters referenced by a number are called **positional - parameters referenced by a number are called **positional
parameters** and reflect the arguments given to a shell parameters** and reflect the arguments given to a shell
- parameters referenced by a **special symbol** are auto-set - parameters referenced by a **special symbol** are auto-set
@ -25,10 +25,10 @@ check what it can be, try the overview section below!
**Arrays** can be special cases for parameter expansion, every **Arrays** can be special cases for parameter expansion, every
applicable description mentions arrays below. Please also see the applicable description mentions arrays below. Please also see the
[article about arrays](/syntax/arrays). [article about arrays](../syntax/arrays.md).
For a more technical view what a parameter is and which types exist, For a more technical view what a parameter is and which types exist,
[see the dictionary entry for \"parameter\"](/dict/terms/parameter). [see the dictionary entry for \"parameter\"](../dict/terms/parameter.md).
## Overview ## Overview
@ -113,7 +113,7 @@ positional parameters (arguments to a script) beyond `$9`:
### Simple usage: Arrays ### Simple usage: Arrays
See also the [article about general array syntax](/syntax/arrays) See also the [article about general array syntax](../syntax/arrays.md)
For arrays you always need the braces. The arrays are expanded by For arrays you always need the braces. The arrays are expanded by
individual indexes or mass arguments. An individual index behaves like a individual indexes or mass arguments. An individual index behaves like a
@ -172,15 +172,15 @@ prefix to the parameter name. Specifically, indirection isn\'t possible
on the `${!var@}`, `${!var*}`, `${!var[@]}`, `${!var[*]}`, and `${#var}` on the `${!var@}`, `${!var*}`, `${!var[@]}`, `${!var[*]}`, and `${#var}`
forms. This means the `!` prefix can\'t be used to retrieve the indices forms. This means the `!` prefix can\'t be used to retrieve the indices
of an array, the length of a string, or number of elements in an array of an array, the length of a string, or number of elements in an array
indirectly (see [syntax/arrays#indirection](syntax/arrays#indirection) indirectly (see [syntax/arrays#indirection](../syntax/arrays.md#indirection)
for workarounds). Additionally, the `!`-prefixed parameter expansion for workarounds). Additionally, the `!`-prefixed parameter expansion
conflicts with ksh-like shells which have the more powerful conflicts with ksh-like shells which have the more powerful
\"name-reference\" form of indirection, where the exact same syntax is \"name-reference\" form of indirection, where the exact same syntax is
used to expand to the name of the variable being referenced. used to expand to the name of the variable being referenced.
Indirect references to [array names](/syntax/arrays) are also possible Indirect references to [array names](../syntax/arrays.md) are also possible
since the Bash 3 series (exact version unknown), but undocumented. See since the Bash 3 series (exact version unknown), but undocumented. See
[syntax/arrays#indirection](syntax/arrays#indirection) for details. [syntax/arrays#indirection](../syntax/arrays.md#indirection) for details.
Chet has added an initial implementation of the ksh `nameref` Chet has added an initial implementation of the ksh `nameref`
declaration command to the git devel branch. (`declare -n`, `local -n`, declaration command to the git devel branch. (`declare -n`, `local -n`,
@ -237,7 +237,7 @@ names or titles. Just assign it to an array:
`declare -a title=(my hello world john smith)` `declare -a title=(my hello world john smith)`
For [array](/syntax/arrays) expansion, the case modification applies to For [array](../syntax/arrays.md) expansion, the case modification applies to
**every expanded element, no matter if you expand an individual index or **every expanded element, no matter if you expand an individual index or
mass-expand** the whole array using `@` or `*` subscripts. Some mass-expand** the whole array using `@` or `*` subscripts. Some
examples: examples:
@ -275,7 +275,7 @@ This will show all defined variable names (not values!) beginning with
$ echo ${!BASH*} $ echo ${!BASH*}
BASH BASH_ARGC BASH_ARGV BASH_COMMAND BASH_LINENO BASH_SOURCE BASH_SUBSHELL BASH_VERSINFO BASH_VERSION BASH BASH_ARGC BASH_ARGV BASH_COMMAND BASH_LINENO BASH_SOURCE BASH_SUBSHELL BASH_VERSINFO BASH_VERSION
This list will also include [array names](/syntax/arrays). This list will also include [array names](../syntax/arrays.md).
## Substring removal ## Substring removal
@ -290,7 +290,7 @@ This list will also include [array names](/syntax/arrays).
This one can **expand only a part** of a parameter\'s value, **given a This one can **expand only a part** of a parameter\'s value, **given a
pattern to describe what to remove** from the string. The pattern is pattern to describe what to remove** from the string. The pattern is
interpreted just like a pattern to describe a filename to match interpreted just like a pattern to describe a filename to match
(globbing). See [Pattern matching](/syntax/pattern) for more. (globbing). See [Pattern matching](../syntax/pattern.md) for more.
Example string (*just a quote from a big man*): Example string (*just a quote from a big man*):
@ -300,7 +300,7 @@ Example string (*just a quote from a big man*):
`${PARAMETER#PATTERN}` and `${PARAMETER##PATTERN}` `${PARAMETER#PATTERN}` and `${PARAMETER##PATTERN}`
This form is to remove the described [pattern](/syntax/pattern) trying This form is to remove the described [pattern](../syntax/pattern.md) trying
to **match it from the beginning of the string**. The operator \"`#`\" to **match it from the beginning of the string**. The operator \"`#`\"
will try to remove the shortest text matching the pattern, while will try to remove the shortest text matching the pattern, while
\"`##`\" tries to do it with the longest text matching. Look at the \"`##`\" tries to do it with the longest text matching. Look at the
@ -353,7 +353,7 @@ on your needs, you might need to adjust shortest/longest match.
### Substring removal: Arrays ### Substring removal: Arrays
As for most parameter expansion features, working on As for most parameter expansion features, working on
[arrays](/syntax/arrays) **will handle each expanded element**, for [arrays](../syntax/arrays.md) **will handle each expanded element**, for
individual expansion and also for mass expansion. individual expansion and also for mass expansion.
Simple example, removing a trailing `is` from all array elements (on Simple example, removing a trailing `is` from all array elements (on
@ -378,7 +378,7 @@ All other variants of this expansion behave the same.
`${PARAMETER//PATTERN}` `${PARAMETER//PATTERN}`
This one can substitute (*replace*) a substring [matched by a This one can substitute (*replace*) a substring [matched by a
pattern](/syntax/pattern), on expansion time. The matched substring will pattern](../syntax/pattern.md), on expansion time. The matched substring will
be entirely removed and the given string will be inserted. Again some be entirely removed and the given string will be inserted. Again some
example string for the tests: example string for the tests:
@ -438,7 +438,7 @@ specifying an empty replacement:
### Search and replace: Arrays ### Search and replace: Arrays
This parameter expansion type applied to [arrays](/syntax/arrays) This parameter expansion type applied to [arrays](../syntax/arrays.md)
**applies to all expanded elements**, no matter if an individual element **applies to all expanded elements**, no matter if an individual element
is expanded, or all elements using the mass expansion syntaxes. is expanded, or all elements using the mass expansion syntaxes.
@ -472,7 +472,7 @@ There\'s not much to say about it, mh?
### (String) length: Arrays ### (String) length: Arrays
For [arrays](/syntax/arrays), this expansion type has two meanings: For [arrays](../syntax/arrays.md), this expansion type has two meanings:
- For **individual** elements, it reports the string length of the - For **individual** elements, it reports the string length of the
element (as for every \"normal\" parameter) element (as for every \"normal\" parameter)
@ -507,7 +507,7 @@ is negative, it\'s taken as a second offset into the string, counting
from the end of the string. from the end of the string.
`OFFSET` and `LENGTH` can be **any** [arithmetic `OFFSET` and `LENGTH` can be **any** [arithmetic
expression](/syntax/arith_expr). **Take care:** The `OFFSET` starts at expression](../syntax/arith_expr.md). **Take care:** The `OFFSET` starts at
0, not at 1! 0, not at 1!
Example string (a quote from a big man): Example string (a quote from a big man):
@ -544,7 +544,7 @@ the colon:
${MYSTRING:(-10):5} ${MYSTRING:(-10):5}
Why? Because it\'s interpreted as the parameter expansion syntax to [use Why? Because it\'s interpreted as the parameter expansion syntax to [use
a default value](/syntax/pe#use_a_default_value). a default value](../syntax/pe.md#use_a_default_value).
### Negative Length Value ### Negative Length Value
@ -558,11 +558,11 @@ then:
`<del>Be liberal </del>in what you accept, and conservative<del> in what you send</del>` `<del>Be liberal </del>in what you accept, and conservative<del> in what you send</del>`
This works since Bash 4.2-alpha, see also This works since Bash 4.2-alpha, see also
[bashchanges](/scripting/bashchanges). [bashchanges](../scripting/bashchanges.md).
### Substring/Element expansion: Arrays ### Substring/Element expansion: Arrays
For [arrays](/syntax/arrays), this expansion type has again 2 meanings: For [arrays](../syntax/arrays.md), this expansion type has again 2 meanings:
- For **individual** elements, it expands to the specified substring - For **individual** elements, it expands to the specified substring
(as for every "normal" parameter) (as for every "normal" parameter)
@ -609,7 +609,7 @@ gender. Note that the default value is **used on expansion time**, it is
### Use a default value: Arrays ### Use a default value: Arrays
For [arrays](/syntax/arrays), the behaviour is very similar. Again, you For [arrays](../syntax/arrays.md), the behaviour is very similar. Again, you
have to make a difference between expanding an individual element by a have to make a difference between expanding an individual element by a
given index and mass-expanding the array using the `@` and `*` given index and mass-expanding the array using the `@` and `*`
subscripts. subscripts.
@ -671,7 +671,7 @@ Example code (please try the example cases yourself):
`${PARAMETER=WORD}` `${PARAMETER=WORD}`
This one works like the [using default This one works like the [using default
values](/syntax/pe#use_a_default_value), but the default text you give values](../syntax/pe.md#use_a_default_value), but the default text you give
is not only expanded, but also **assigned** to the parameter, if it was is not only expanded, but also **assigned** to the parameter, if it was
unset or null. Equivalent to using a default value, when you omit the unset or null. Equivalent to using a default value, when you omit the
`:` (colon), as shown in the second form, the default value will only be `:` (colon), as shown in the second form, the default value will only be
@ -693,7 +693,7 @@ Let\'s change our code example from above:
### Assign a default value: Arrays ### Assign a default value: Arrays
For [arrays](/syntax/arrays) this expansion type is limited. For an For [arrays](../syntax/arrays.md) this expansion type is limited. For an
individual index, it behaves like for a \"normal\" parameter, the individual index, it behaves like for a \"normal\" parameter, the
default value is assigned to this one element. The mass-expansion default value is assigned to this one element. The mass-expansion
subscripts `@` and `*` **can not be used here** because it\'s not subscripts `@` and `*` **can not be used here** because it\'s not
@ -742,7 +742,7 @@ if variables you need (and that can be empty) are undefined:
### Use an alternate value: Arrays ### Use an alternate value: Arrays
Similar to the cases for [arrays](/syntax/arrays) to expand to a default Similar to the cases for [arrays](../syntax/arrays.md) to expand to a default
value, this expansion behaves like for a \"normal\" parameter when using value, this expansion behaves like for a \"normal\" parameter when using
individual array elements by index, but reacts differently when using individual array elements by index, but reacts differently when using
the mass-expansion subscripts `@` and `*`: the mass-expansion subscripts `@` and `*`:
@ -819,8 +819,8 @@ Removing the first 6 characters from a text string:
`${arr[@]}`, `$*`, and `${arr[*]}` when `${arr[@]}`, `$*`, and `${arr[*]}` when
[IFS](http://mywiki.wooledge.org/IFS) is set to null. POSIX is [IFS](http://mywiki.wooledge.org/IFS) is set to null. POSIX is
unclear about the expected behavior. A null IFS causes both [word unclear about the expected behavior. A null IFS causes both [word
splitting](/syntax/expansion/wordsplit) and [pathname splitting](../syntax/expansion/wordsplit.md) and [pathname
expansion](/syntax/expansion/globs) to behave randomly. Since there expansion](../syntax/expansion/globs.md) to behave randomly. Since there
are few good reasons to leave `IFS` set to null for more than the are few good reasons to leave `IFS` set to null for more than the
duration of a command or two, and even fewer to expand `$@` and `$*` duration of a command or two, and even fewer to expand `$@` and `$*`
unquoted, this should be a rare issue. **Always quote unquoted, this should be a rare issue. **Always quote
@ -1051,6 +1051,6 @@ the difference may introduce a possible compatibility problem.
## See also ## See also
- Internal: [Introduction to expansion and - Internal: [Introduction to expansion and
substitution](/syntax/expansion/intro) substitution](../syntax/expansion/intro.md)
- Internal: [Arrays](/syntax/arrays) - Internal: [Arrays](../syntax/arrays.md)
- Dictionary, internal: [parameter](/dict/terms/parameter) - Dictionary, internal: [parameter](../dict/terms/parameter.md)

View File

@ -71,14 +71,14 @@ meaning to bash. [Exception:]{.underline} Inside a single-quoted string
Inside a weak-quoted string there\'s **no special interpretion of**: Inside a weak-quoted string there\'s **no special interpretion of**:
- spaces as word-separators (on inital command line splitting and on - spaces as word-separators (on inital command line splitting and on
[word splitting](/syntax/expansion/wordsplit)!) [word splitting](../syntax/expansion/wordsplit.md)!)
- single-quotes to introduce strong-quoting (see below) - single-quotes to introduce strong-quoting (see below)
- characters for pattern matching - characters for pattern matching
- tilde expansion - tilde expansion
- pathname expansion - pathname expansion
- process substitution - process substitution
Everything else, especially [parameter expansion](/syntax/pe), is Everything else, especially [parameter expansion](../syntax/pe.md), is
performed! performed!
ls -l "*" ls -l "*"
@ -197,7 +197,7 @@ documentation](http://www.gnu.org/software/gettext/manual/html_node/bash.html)
### String lists in for-loops ### String lists in for-loops
The [classic for loop](/syntax/ccmd/classic_for) uses a list of words to The [classic for loop](../syntax/ccmd/classic_for.md) uses a list of words to
iterate through. The list can also be in a variable: iterate through. The list can also be in a variable:
mylist="DOG CAT BIRD HORSE" mylist="DOG CAT BIRD HORSE"
@ -221,7 +221,7 @@ is seen as **one word**. The for loop iterates exactly one time, with
### Working out the test-command ### Working out the test-command
The command `test` or `[ ... ]` ([the classic test The command `test` or `[ ... ]` ([the classic test
command](/commands/classictest)) is an ordinary command, so ordinary command](../commands/classictest.md)) is an ordinary command, so ordinary
syntax rules apply. Let\'s take string comparison as an example: syntax rules apply. Let\'s take string comparison as an example:
[ WORD = WORD ] [ WORD = WORD ]
@ -259,16 +259,16 @@ Now the command has three parameters, which makes sense for a binary
(two argument) operator. (two argument) operator.
**[Hint:]{.underline}** Inside the [conditional **[Hint:]{.underline}** Inside the [conditional
expression](/syntax/ccmd/conditional_expression) (`[[ ]]`) Bash doesn\'t expression](../syntax/ccmd/conditional_expression.md) (`[[ ]]`) Bash doesn\'t
perform word splitting, and thus you don\'t need to quote your variable perform word splitting, and thus you don\'t need to quote your variable
references - they are always seen as \"one word\". references - they are always seen as \"one word\".
## See also ## See also
- Internal: [Some words about words\...](/syntax/words) - Internal: [Some words about words\...](../syntax/words.md)
- Internal: [Word splitting](/syntax/expansion/wordsplit) - Internal: [Word splitting](../syntax/expansion/wordsplit.md)
- Internal: [Introduction to expansions and - Internal: [Introduction to expansions and
substitutions](/syntax/expansion/intro) substitutions](../syntax/expansion/intro.md)
```{=html} ```{=html}
<!-- --> <!-- -->

View File

@ -5,7 +5,7 @@ Redirection makes it possible to control where the output of a command
goes to, and where the input of a command comes from. It\'s a mighty goes to, and where the input of a command comes from. It\'s a mighty
tool that, together with pipelines, makes the shell powerful. The tool that, together with pipelines, makes the shell powerful. The
redirection operators are checked whenever a [simple command is about to redirection operators are checked whenever a [simple command is about to
be executed](/syntax/grammar/parser_exec). be executed](../syntax/grammar/parser_exec.md).
Under normal circumstances, there are 3 files open, accessible by the Under normal circumstances, there are 3 files open, accessible by the
file descriptors 0, 1 and 2, all connected to your terminal: file descriptors 0, 1 and 2, all connected to your terminal:
@ -79,7 +79,7 @@ This redirects the file descriptor number `N` to the target `TARGET`. If
**truncated** before writing starts. **truncated** before writing starts.
If the option `noclobber` is set with [the set If the option `noclobber` is set with [the set
builtin](/commands/builtin/set), with cause the redirection to fail, builtin](../commands/builtin/set.md), with cause the redirection to fail,
when `TARGET` names a regular file that already exists. You can manually when `TARGET` names a regular file that already exists. You can manually
override that behaviour by forcing overwrite with the redirection override that behaviour by forcing overwrite with the redirection
operator `>|` instead of `>`. operator `>|` instead of `>`.
@ -108,7 +108,7 @@ Since Bash4, there\'s `&>>TARGET`, which is equivalent to
\<wrap center important\>This syntax is deprecated and should not be \<wrap center important\>This syntax is deprecated and should not be
used. See the page about [obsolete and deprecated used. See the page about [obsolete and deprecated
syntax](/scripting/obsolete).\</wrap\> syntax](../scripting/obsolete.md).\</wrap\>
## Appending redirected output and error output ## Appending redirected output and error output
@ -160,9 +160,9 @@ used to mark the end of input later:
As you see, substitutions are possible. To be precise, the following As you see, substitutions are possible. To be precise, the following
substitutions and expansions are performed in the here-document data: substitutions and expansions are performed in the here-document data:
- [Parameter expansion](/syntax/pe) - [Parameter expansion](../syntax/pe.md)
- [Command substitution](/syntax/expansion/cmdsubst) - [Command substitution](../syntax/expansion/cmdsubst.md)
- [Arithmetic expansion](/syntax/expansion/arith) - [Arithmetic expansion](../syntax/expansion/arith.md)
You can avoid that by quoting the tag: You can avoid that by quoting the tag:
@ -238,14 +238,14 @@ How to make a program quiet (assuming all output goes to `STDOUT` and
## See also ## See also
- Internal: [Illustrated Redirection - Internal: [Illustrated Redirection
Tutorial](/howto/redirection_tutorial) Tutorial](../howto/redirection_tutorial.md)
- Internal: [The noclobber - Internal: [The noclobber
option](/commands/builtin/set#tag_noclobber) option](../commands/builtin/set.md#tag_noclobber)
- Internal: [The exec builtin command](/commands/builtin/exec) - Internal: [The exec builtin command](../commands/builtin/exec.md)
- Internal: [Simple commands parsing and - Internal: [Simple commands parsing and
execution](/syntax/grammar/parser_exec) execution](../syntax/grammar/parser_exec.md)
- Internal: [Process substitution - Internal: [Process substitution
syntax](/syntax/expansion/proc_subst) syntax](../syntax/expansion/proc_subst.md)
- Internal: [Obsolete and deprecated syntax](/scripting/obsolete) - Internal: [Obsolete and deprecated syntax](../scripting/obsolete.md)
- Internal: [Nonportable syntax and command - Internal: [Nonportable syntax and command
uses](/scripting/nonportable) uses](../scripting/nonportable.md)

View File

@ -5,23 +5,23 @@
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
parameter character expansion description parameter character expansion description
----------- ------------------ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------- ------------------ -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`*` asterisk The positional parameters starting from the first. When used inside doublequotes (see [quoting](/syntax/quoting)), like `"$*"`, it expands to all positional parameters *as one word*, delimited by the first character of the `IFS` variable (a space in this example): `"$1 $2 $3 $4"`.\ `*` asterisk The positional parameters starting from the first. When used inside doublequotes (see [quoting](../syntax/quoting.md)), like `"$*"`, it expands to all positional parameters *as one word*, delimited by the first character of the `IFS` variable (a space in this example): `"$1 $2 $3 $4"`.\
If `IFS` is unset, the delimiter used will be always a space, if `IFS` is NULL, the delimiter will be nothing, which effectively concatenates all the positional parameters without any delimiter.\ If `IFS` is unset, the delimiter used will be always a space, if `IFS` is NULL, the delimiter will be nothing, which effectively concatenates all the positional parameters without any delimiter.\
When used unquoted, it will just expand to the strings, one by one, not preserving the word boundaries (i.e. word splitting will split the text again, if it contains `IFS` characters.\ When used unquoted, it will just expand to the strings, one by one, not preserving the word boundaries (i.e. word splitting will split the text again, if it contains `IFS` characters.\
See also the [scripting article about handling positional parameters](/scripting/posparams). See also the [scripting article about handling positional parameters](../scripting/posparams.md).
`@` at-sign The positional parameters starting from the first. When used inside doublequotes (see [quoting](/syntax/quoting)), like `"$@"`, it expands all positional parameters *as separate words*: `"$1" "$2" "$3" "$4"`\ `@` at-sign The positional parameters starting from the first. When used inside doublequotes (see [quoting](../syntax/quoting.md)), like `"$@"`, it expands all positional parameters *as separate words*: `"$1" "$2" "$3" "$4"`\
Without doublequotes, the behaviour is like the one of `*` without doublequotes.\ Without doublequotes, the behaviour is like the one of `*` without doublequotes.\
See also the [scripting article about handling positional parameters](/scripting/posparams). See also the [scripting article about handling positional parameters](../scripting/posparams.md).
`#` hash mark Number of positional parameters (decimal)\ `#` hash mark Number of positional parameters (decimal)\
See also the [scripting article about handling positional parameters](/scripting/posparams). See also the [scripting article about handling positional parameters](../scripting/posparams.md).
`?` question mark Status of the most recently executed foreground-pipeline (exit/return code) `?` question mark Status of the most recently executed foreground-pipeline (exit/return code)
`-` dash Current option flags set by the shell itself, on invocation, or using the [set builtin command](/commands/builtin/set). It\'s just a set of characters, like `himB` for `h`, `i`, `m` and `B`. `-` dash Current option flags set by the shell itself, on invocation, or using the [set builtin command](../commands/builtin/set.md). It\'s just a set of characters, like `himB` for `h`, `i`, `m` and `B`.
`$` dollar-sign The process ID (PID) of the shell. In an [explicit subshell](/syntax/ccmd/grouping_subshell) it expands to the PID of the current \"main shell\", not the subshell. This is different from `$BASHPID`! `$` dollar-sign The process ID (PID) of the shell. In an [explicit subshell](../syntax/ccmd/grouping_subshell.md) it expands to the PID of the current \"main shell\", not the subshell. This is different from `$BASHPID`!
`!` exclamation mark The process ID (PID) of the most recently executed background pipeline (like started with `command &`) `!` exclamation mark The process ID (PID) of the most recently executed background pipeline (like started with `command &`)
@ -54,7 +54,7 @@ Bash.
A colon-separated list of enabled shell options. A colon-separated list of enabled shell options.
Each word in the list is a valid argument for the `-s` option to the Each word in the list is a valid argument for the `-s` option to the
[shopt builtin command](/commands/builtin/shopt). The options appearing [shopt builtin command](../commands/builtin/shopt.md). The options appearing
in `BASHOPTS` are those reported as on by `shopt`. If this variable is in `BASHOPTS` are those reported as on by `shopt`. If this variable is
in the environment when Bash starts up, each shell option in the list in the environment when Bash starts up, each shell option in the list
will be enabled before reading any startup files. will be enabled before reading any startup files.
@ -89,7 +89,7 @@ this array appear in the alias list; unsetting array elements cause
aliases to be removed from the alias list. aliases to be removed from the alias list.
The associative key is the name of the alias as used with the [alias The associative key is the name of the alias as used with the [alias
builtin command](/commands/builtin/alias). builtin command](../commands/builtin/alias.md).
### BASH_ARGC ### BASH_ARGC
@ -103,7 +103,7 @@ frame of the current Bash execution call stack.
The number of parameters to the current subroutine (shell function or The number of parameters to the current subroutine (shell function or
script executed with [`.` or `source` builtin script executed with [`.` or `source` builtin
command](/commands/builtin/source)) is at the top of the stack. When a command](../commands/builtin/source.md)) is at the top of the stack. When a
subroutine is executed, the number of parameters passed is pushed onto subroutine is executed, the number of parameters passed is pushed onto
`BASH_ARGC`. `BASH_ARGC`.
@ -145,12 +145,12 @@ subsequently reset.
An associative array variable whose members correspond to the internal An associative array variable whose members correspond to the internal
hash table of commands as maintained by the [hash builtin hash table of commands as maintained by the [hash builtin
command](/commands/builtin/hash). Elements added to this array appear in command](../commands/builtin/hash.md). Elements added to this array appear in
the hash table; unsetting array elements cause commands to be removed the hash table; unsetting array elements cause commands to be removed
from the hash table. from the hash table.
The associative key is the name of the command as used with the[hash The associative key is the name of the command as used with the[hash
builtin command](/commands/builtin/hash). builtin command](../commands/builtin/hash.md).
### BASH_COMMAND ### BASH_COMMAND
@ -454,7 +454,7 @@ element of `FUNCNAME` has corresponding elements in `BASH_LINENO` and
`BASH_SOURCE` to describe the call stack. For instance, `BASH_SOURCE` to describe the call stack. For instance,
`${FUNCNAME[$i]}` was called from the file `${BASH_SOURCE[$i+1]}` at `${FUNCNAME[$i]}` was called from the file `${BASH_SOURCE[$i+1]}` at
line number `${BASH_LINENO[$i]}`. The [caller builtin line number `${BASH_LINENO[$i]}`. The [caller builtin
command](/commands/builtin/caller) displays the current call stack using command](../commands/builtin/caller.md) displays the current call stack using
this information. this information.
This variable exists only when a shell function is executing. This variable exists only when a shell function is executing.
@ -555,7 +555,7 @@ Example content:
Set by Bash: yes Default: n/a Set by Bash: yes Default: n/a
An array variable created to hold the text read by the [mapfile builtin An array variable created to hold the text read by the [mapfile builtin
command](/commands/builtin/mapfile) when no variable name is supplied. command](../commands/builtin/mapfile.md) when no variable name is supplied.
### OLDPWD ### OLDPWD
@ -574,7 +574,7 @@ The previous working directory as set by the cd command.
Set by Bash: yes Default: n/a Set by Bash: yes Default: n/a
The value of the last option argument processed by the [getopts builtin The value of the last option argument processed by the [getopts builtin
command](/commands/builtin/getopts). command](../commands/builtin/getopts.md).
### OPTIND ### OPTIND
@ -584,7 +584,7 @@ command](/commands/builtin/getopts).
Set by Bash: yes Default: n/a Set by Bash: yes Default: n/a
The index of the next argument to be processed by the [getopts builtin The index of the next argument to be processed by the [getopts builtin
command](/commands/builtin/getopts). command](../commands/builtin/getopts.md).
### OSTYPE ### OSTYPE
@ -628,7 +628,7 @@ The process ID of the shell\'s parent process.
Set by Bash: yes Default: n/a Set by Bash: yes Default: n/a
The current working directory as set by the [cd builtin The current working directory as set by the [cd builtin
command](/commands/builtin/cd). command](../commands/builtin/cd.md).
### RANDOM ### RANDOM
@ -668,10 +668,10 @@ with `bind -x`.
Variable: `REPLY` Since: unknown Variable: `REPLY` Since: unknown
-------------- ------------------------------------------------------------ ------------ --------- -------------- ------------------------------------------------------------ ------------ ---------
Type: normal variable Read-only: no Type: normal variable Read-only: no
Set by Bash: only by the [read builtin command](/commands/builtin/read) Default: n/a Set by Bash: only by the [read builtin command](../commands/builtin/read.md) Default: n/a
Set to the line of input read by the [read builtin Set to the line of input read by the [read builtin
command](/commands/builtin/read) when no arguments are supplied that command](../commands/builtin/read.md) when no arguments are supplied that
name target variables. name target variables.
### SECONDS ### SECONDS
@ -698,7 +698,7 @@ is subsequently reset.
A colon-separated list of enabled shell options. Each word in the list 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 is a valid argument for the `-o` option to the [set builtin
command](/commands/builtin/set). The options appearing in `SHELLOPTS` command](../commands/builtin/set.md). The options appearing in `SHELLOPTS`
are those reported as on by `set -o`. are those reported as on by `set -o`.
If this variable is in the environment when Bash starts up, each shell If this variable is in the environment when Bash starts up, each shell
@ -736,9 +736,9 @@ If this parameter is set when Bash is executing a shell script, its
value is interpreted as a filename containing commands to initialize the value is interpreted as a filename containing commands to initialize the
shell, as in `~/.bashrc`. The value of `BASH_ENV` is subjected to shell, as in `~/.bashrc`. The value of `BASH_ENV` is subjected to
- [parameter expansion](/syntax/pe) - [parameter expansion](../syntax/pe.md)
- [command substitution](/syntax/expansion/cmdsubst) - [command substitution](../syntax/expansion/cmdsubst.md)
- [arithmetic expansion](/syntax/expansion/arith) - [arithmetic expansion](../syntax/expansion/arith.md)
before being interpreted as a file name. before being interpreted as a file name.
@ -770,7 +770,7 @@ unsetting it will result in the standard error being closed.
Type: normal variable Read-only: no Type: normal variable Read-only: no
Set by Bash: no Default: n/a Set by Bash: no Default: n/a
The search path for the [cd builtin command](/commands/builtin/cd). The search path for the [cd builtin command](../commands/builtin/cd.md).
This is a colon-separated list of directories in which the shell looks This is a colon-separated list of directories in which the shell looks
for destination directories specified by the `cd` command. for destination directories specified by the `cd` command.
@ -828,7 +828,7 @@ Similar to `BASH_ENV`: Used when the shell is invoked in POSIX(r) mode.
Type: normal variable Read-only: no Type: normal variable Read-only: no
Set by Bash: no Default: n/a Set by Bash: no Default: n/a
The default editor for the [fc builtin command](/commands/builtin/fc). The default editor for the [fc builtin command](../commands/builtin/fc.md).
### FIGNORE ### FIGNORE
@ -986,10 +986,10 @@ comment character to distinguish timestamps from other history lines.
The home directory of the current user. The home directory of the current user.
The default argument for the [cd builtin command](/commands/builtin/cd). The default argument for the [cd builtin command](../commands/builtin/cd.md).
The value of this variable is also used when performing [tilde The value of this variable is also used when performing [tilde
expansion](/syntax/expansion/tilde). expansion](../syntax/expansion/tilde.md).
### HOSTFILE ### HOSTFILE
@ -1177,7 +1177,7 @@ Example content:
Set by Bash: yes Default: 1 (set on startup) Set by Bash: yes Default: 1 (set on startup)
If set to the value 1, Bash displays error messages generated by the If set to the value 1, Bash displays error messages generated by the
[getopts builtin command](/commands/builtin/getopts). [getopts builtin command](../commands/builtin/getopts.md).
`OPTERR` is initialized to 1 each time the shell is invoked or a shell `OPTERR` is initialized to 1 each time the shell is invoked or a shell
script is executed. script is executed.
@ -1368,9 +1368,9 @@ A trailing newline is added when the format string is displayed.
Set by Bash: no Default: n/a Set by Bash: no Default: n/a
If set to a value greater than zero, `TMOUT` is treated as the default If set to a value greater than zero, `TMOUT` is treated as the default
timeout for the [read builtin command](/commands/builtin/read). timeout for the [read builtin command](../commands/builtin/read.md).
The [select command](/commands/builtin/select) terminates if input does The [select command](../commands/builtin/select.md) terminates if input does
not arrive after `TMOUT` seconds when input is coming from a terminal. not arrive after `TMOUT` seconds when input is coming from a terminal.
In an interactive shell, the value is interpreted as the number of In an interactive shell, the value is interpreted as the number of

View File

@ -90,7 +90,7 @@ take care of the spaces. But Bash also does another type of splitting.
## Word splitting ## Word splitting
For a more technical description, please read the [article about word For a more technical description, please read the [article about word
splitting](/syntax/expansion/wordsplit)! splitting](../syntax/expansion/wordsplit.md)!
The first kind of splitting is done to parse the command line into The first kind of splitting is done to parse the command line into
separate tokens. This is what was described above, it\'s a pure separate tokens. This is what was described above, it\'s a pure
@ -139,9 +139,9 @@ the command line\"):
Word 1 Word 2 Word 3 Word 4 Word 5 Word 6 Word 1 Word 2 Word 3 Word 4 Word 5 Word 6
`echo` `The` `file` `is` `named` `$MYFILE` `echo` `The` `file` `is` `named` `$MYFILE`
A [parameter/variable expansion](/syntax/pe) is part of that command A [parameter/variable expansion](../syntax/pe.md) is part of that command
line, Bash will perform the substitution, and the [word line, Bash will perform the substitution, and the [word
splitting](/syntax/expansion/wordsplit) on the results: splitting](../syntax/expansion/wordsplit.md) on the results:
Word splitting after substitution: Word splitting after substitution:
------------------------------------ -------- -------- -------- --------- -------- ------------ ------------------------------------ -------- -------- -------- --------- -------- ------------
@ -159,10 +159,10 @@ Now let\'s imagine we quoted `$MYFILE`, the command line now looks like:
***Bold Text*72i love this world**===== See also ===== ***Bold Text*72i love this world**===== See also =====
- Internal: [Quoting and character escaping](/syntax/quoting) - Internal: [Quoting and character escaping](../syntax/quoting.md)
- Internal: [Word splitting](/syntax/expansion/wordsplit) - Internal: [Word splitting](../syntax/expansion/wordsplit.md)
- Internal: [Introduction to expansions and - Internal: [Introduction to expansions and
substitutions](/syntax/expansion/intro) substitutions](../syntax/expansion/intro.md)
```{=html} ```{=html}
<!-- --> <!-- -->