Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Commit

Permalink
Add notes for dynamic variables
Browse files Browse the repository at this point in the history
  • Loading branch information
FriendlyNeighborhoodShane committed Sep 12, 2020
1 parent db7942c commit b57b856
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -679,9 +679,33 @@ done

## Name and access a variable based on another variable

### Set the dynamic part of the variable name

```shell
$ var="world"
```

#### Option [1]: Set the variable using export

**Warning:** Actually exports the variable, it will be inherited by called programs. Remember to unset.

```shell
$ export "hello_$var=value"
```

#### Option [2]: Set the variable using eval

**Warning:** Does not export the variables, but is more dangerous than using export, as eval can execute arbitrary commands (try with `var="=;echo pwned;_"`). Remember to sanitize any data to only have alphanumerals and underscores.

This comment has been minimized.

Copy link
@spiralofhope

spiralofhope Oct 10, 2020

Remember to sanitize any data to only have alphanumerals and underscores.

I wonder; would this be a valuable script for me to make?


```shell
$ eval "hello_$var=value"
```

### Access the variable in a command

**NOTE:** The entire sequence is interpreted an extra time by the shell when calling eval. Note the double-escaping in the printf format.

```shell
$ eval printf '%s\\n' "\$hello_$var"
value
```
Expand Down

0 comments on commit b57b856

Please sign in to comment.