Issue
Please take some time to help me with this part(shell scripting)
I have a code that is
helper()
{
var1="$1"
#multiple lines of code
.
.
#so the variable must be created based on what value is passed as an argument.
$var1_var_name="some string"
#so I should be able to make a varible abc_var_name in this case
}
helper "abc"
So I want to create a variable inside helper function such that that variable name would be
if helper "abc" is called then the variable should be abc_var_name="some string"
or if helper "def" is called then the variable should be def_var_name="some string"
Solution
You probably want namerefs (with a recent enough version of bash):
$ helper() {
declare -n tmp="$1"_var_name
tmp="some string"
}
$ helper "abc"
$ echo "$abc_var_name"
some string
If your version of bash is too old you can also use read
to set a named variable:
$ helper() {
IFS= read -r "$1"_var_name <<< "some string"
}
$ helper "abc"
$ echo "$abc_var_name"
some string
Or printf
:
$ helper() {
printf -v "$1"_var_name '%s' "some string"
}
$ helper "abc"
$ echo "$abc_var_name"
some string
For completeness, as suggested in comments, if you accept to slightly change your approach, associative arrays are another option: all your named variables become elements of associative array var_name
, the keys of the array are the names you pass to your function, and the values are whatever you want. One important benefit is that you can easily loop over all your variables:
$ declare -A var_name=()
$ helper() {
var_name["$1"]="some string"
}
$ helper "abc"
$ helper "def"
$ for key in "${!var_name[@]}"; do
printf '%s: %s\n' "$key" "${var_name[$key]}"
done
def: some string
abc: some string
Answered By - Renaud Pacalet Answer Checked By - Marilyn (WPSolving Volunteer)