From b57b8567b32ec27fc50e949bfd773d31c0a54fbe Mon Sep 17 00:00:00 2001 From: FriendlyNeighborhoodShane Date: Mon, 27 Jul 2020 00:19:07 +0530 Subject: [PATCH] Add notes for dynamic variables --- README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README.md b/README.md index 8006cea..b1aa001 100644 --- a/README.md +++ b/README.md @@ -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. + +```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 ```