pure-bash-bible/manuscript/chapter6.txt

41 lines
581 B
Plaintext
Raw Normal View History

2018-06-20 08:00:33 +02:00
# VARIABLES
2018-06-20 05:03:53 +02:00
## Assign and access a variable using a variable
2018-06-20 05:03:53 +02:00
```shell
2019-01-19 10:20:13 +01:00
$ hello_world="value"
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"
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.
$ 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
```
## Name a variable based on another variable
```shell
$ var="world"
$ declare "hello_$var=value"
$ printf '%s\n' "$hello_world"
value
```
<!-- CHAPTER END -->