Size: 1656
Comment:
|
← Revision 7 as of 2023-01-30 01:51:15 ⇥
Size: 2296
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 19: | Line 19: |
A variable can be declared without a value, and this is distinct from not being set. {{{ declare d }}} |
|
Line 27: | Line 33: |
And as with `declare`, variables can be set empty. {{{ d= }}} |
|
Line 28: | Line 40: |
Within a function, [[Bash/Function#Local_Scope|local variables]] can be declared with the `local` [[Bash/BuiltinCommands#Local|builtin]]. {{{ local a=1 b=2 c=3 }}} Note that if `declare` is used within a function, those variables are also locally-scoped. |
|
Line 39: | Line 59: |
b=$a | b=$a # 'foo' |
Line 46: | Line 66: |
b=${a}bar | b=${a}bar # 'foobar' }}} If a variable's value includes a character that the shell will interpret specially, [[Bash/Quoting|quote]] the variable. {{{ a=foo b="$a bar" # 'foo bar' |
Bash Variables
For a list of special variables are used internally by the bash(1) shell, see here.
Declaring
Variables can be explicitly declared with the declare builtin.
declare a=1 b=2 c=3
A variable can be declared without a value, and this is distinct from not being set.
declare d
Variables can also be created implicitly.
a=1 b=2 c=3
And as with declare, variables can be set empty.
d=
For declaring array variables, see here.
Within a function, local variables can be declared with the local builtin.
local a=1 b=2 c=3
Note that if declare is used within a function, those variables are also locally-scoped.
Usage
Variables are accessed by their name. A dollar sign ($) must be prefixed to the name.
a=foo b=$a # 'foo'
To delimit a variable name from string literals, use braces. For example:
a=foo b=${a}bar # 'foobar'
If a variable's value includes a character that the shell will interpret specially, quote the variable.
a=foo b="$a bar" # 'foo bar'
Special Variables
The following variables are set automatically by bash(1).
Variable |
Value |
$# |
number of arguments |
$@ |
all arguments as an array |
$* |
all arguments as a string |
$? |
the exit code |
$$ |
the PID of the shell |
$! |
the PID of the most recent background job |
Positional Variables
The name of a command is stored in $0.
The first argument to the command is stored in $1. And so on until the 9th argument, $9.
From the tenth argument, while arguments are stored in an indexed variable, they must be accessed differently. $10 is interpretted like ${1}0. To actually access the 10th argument, try ${10}.