2018-06-20 08:00:33 +02:00
|
|
|
# VARIABLES
|
2018-06-20 04:24:38 +02:00
|
|
|
|
2018-06-20 05:03:53 +02:00
|
|
|
## Assign and access a variable using a variable
|
2018-06-20 04:24:38 +02:00
|
|
|
|
2018-06-20 05:03:53 +02:00
|
|
|
```shell
|
2019-01-19 10:20:13 +01:00
|
|
|
$ hello_world="value"
|
2018-06-20 04:24:38 +02:00
|
|
|
|
2018-06-20 05:03:53 +02:00
|
|
|
# Create the variable name.
|
2019-01-19 10:20:13 +01:00
|
|
|
$ var="world"
|
|
|
|
$ ref="hello_$var"
|
2018-06-20 04:24:38 +02:00
|
|
|
|
2019-01-19 10:20:13 +01:00
|
|
|
# Print the value of the variable name stored in 'hello_$var'.
|
|
|
|
$ printf '%s\n' "${!ref}"
|
|
|
|
value
|
|
|
|
```
|
|
|
|
|
|
|
|
Alternatively, on `bash` 4.3+:
|
|
|
|
|
|
|
|
```shell
|
|
|
|
$ hello_world="value"
|
|
|
|
$ var="world"
|
|
|
|
|
|
|
|
# Declare a nameref.
|
2019-01-22 06:36:58 +01:00
|
|
|
$ declare -n ref=hello_$var
|
2019-01-19 10:20:13 +01:00
|
|
|
|
|
|
|
$ printf '%s\n' "$ref"
|
|
|
|
value
|
2018-06-20 05:03:53 +02:00
|
|
|
```
|
2018-06-20 04:24:38 +02:00
|
|
|
|
2019-01-19 11:19:19 +01:00
|
|
|
## Name a variable based on another variable
|
|
|
|
|
|
|
|
```shell
|
|
|
|
$ var="world"
|
2019-01-22 06:36:58 +01:00
|
|
|
$ declare "hello_$var=value"
|
2019-01-19 11:19:19 +01:00
|
|
|
$ printf '%s\n' "$hello_world"
|
|
|
|
value
|
|
|
|
```
|
|
|
|
|
2018-06-20 04:24:38 +02:00
|
|
|
<!-- CHAPTER END -->
|
|
|
|
|