how to access an automatically named variable in a Bash shell script - bash

I have some code that creates a variable of some name automatically and assigns some value to it. The code is something like the following:
myVariableName="zappo"
eval "${myVariableName}=zappo_value"
How would I access the value of this variable using the automatically generated name of the variable? So, I'm looking for some code a bit like the following (but working):
eval "echo ${${myVariableName}}"
(... which may be used in something such as myVariableValue="$(eval "echo ${${myVariableName}}")"...).
Thanks muchly for any assistance
If you think this approach is madness and want offer more general advice, the general idea I'm working on is having variables defined in functions in a library with such names as ${usage} and ${prerequisiteFunctions}. These variables that are defined within functions would be accessed by an interrogation function that can, for instance, ensure that prerequisites etc. are installed. So a loop within this interrogation function is something like this:
for currentFunction in ${functionList}; do
echo "function: ${currentFunction}"
${currentFunction} -interrogate # (This puts the function variables into memory.)
currentInterrogationVariables="${interrogationVariables}" # The variable interrogationVariables contains a list of all function variables available for interrogation.
for currentInterrogationVariable in ${currentInterrogationVariables}; do
echo "content of ${currentInterrogationVariable}:"
eval "echo ${${currentInterrogationVariable}}"
done
done
Thanks again for any ideas!

IIRC, indirection in bash is by !, so try ${!myVariableName}

Try:
echo ${!myVariableName}
It will echo the variable who's name is contained in $myVariableName
For example:
#!/bin/bash
VAR1="ONE"
VAR2="TWO"
VARx="VAR1"
echo ${VARx} # prints "VAR1"
echo ${!VARx} # prints "ONE"

Related

Using a string value with the name of an existing variable to get the value of the existing variable

I am using a bash script in an azure devops pipeline where a variable is created dynamically from one of the pipeline tasks.
I need to use the variable's value in subsequent scripts, I can formulate the string which is used for the variable name, however cannot get the value of the variable using this string. I hope the below example makes it clear on what I need.
Thanks in advance for your help.
PartAPartB="This is my text"
echo "$PartAPartB" #Shows "This is my text" as expected
#HOW DO I GET BELOW TO PRINT "This is my text"
#without using the PartAPartB variable and
#using VarAB value to become the variable name
VarAB="PartAPartB"
VARNAME="$VarAB"
echo $("$VARNAME") #INCORRECT
You can use eval to do this
$ PartAPartB="This is my text"
$ VarAB="PartAPartB"
$ eval "echo \${${VarAB}}"
This is my text
You have two choices with bash. Using a nameref with declare -n (which is the preferred approach for Bash >= 4.26) or using variable indirection. In your case, examples of both would be:
#!/bin/bash
VarAB="PartAPartB"
## using a nameref
declare -n VARNAME=VarAB
echo "$VARNAME" # CORRECT
## using indirection
othervar=VarAB
echo "${!othervar}" # Also Correct
(note: do not use ALLCAPS variable names, those a generally reserved for environment variables or system variables)

how to differentiate between function arguments and script arguments

lets say I have a script called hello
$ cat hello
function1 () {
echo $1
}
function1 what
echo $1
and I call
$ sh hello chicken
what
chicken
How do i refer to the script parameters (chicken) inside the function. Would I have to rename all the script arguments or store them somewhere else? Whats the best way to handle this?
This is a case of shadowing, you can find information about it below
https://www.gnu.org/software/bash/manual/html_node/Shell-Functions.html
If you try to picture it, the inner scope variable casts a "shadow" over the outer scope variable and hides it from view. As soon as the inner scope variable is gone, the program can again "find" the outer scope variable.
It's pretty much another variation of a general rule in programming where things that are more specific or refer to an inner scope, override things that are more generic or part of an outer scope.
If you wrote
temp="hi"
phrase(){
echo "$temp"
temp="hello"
echo "$temp"
}
phrase
The result would be
hi
hello
because the variable of the inner scope "overshadows" the variable of the outer scope.
That can be prevented by storing your script's $1 parameter using another name.
So, as you said, the best approach is to make sure all variables have different names by storing your script parameters inside distinctly named variables.
temp=$1
function1 () {
echo "$1"
echo "$temp"
}
function1 what
echo "$1"
Edit: I forgot to account for the fact that script variables are not available directly inside functions like #gordondavisson said, so even if you weren't passing the word "what" as a parameter to your function, you still wouldn't be able to print the word "chicken".
So, in this case, the only possible way to use the parameter inside the function would be to assign $1 to a variable.

Set a value to global variable from a subshell

Code example main.zsh:
#!/usr/bin/env zsh
. ./my_script.zsh
my_global_var=""
output=$(my_func)
Code example my_script.zsh:
#!/usr/bin/env zsh
my_func(){
my_global_var="hello!" # doesn't work!
echo "my output" # return value
}
In this case how can I set a value to my_global_var from my_func in a subshell. What I try to do here, I just try to implement a function concept in zsh which be able to return a value via variable substitution mechanism $() but the problem is if I implement it in this way, I will not be able to access global variable from my function. I'm quite confusing now, maybe I get into the wrong way to implement a function concept in zsh.
You can't. my_func runs in a separate process, so whatever it does to my_global_var is local to that process, unseen by main.zsh. Your function can either be used to set global variables or output text intended to be captured by $(...), not both.
Thank you #chepner for your answer, BTW, I would like to purpose an alternative way to solve this problem. Many people have talked about "return multiple variables", in the same way, here I will purpose you an "eval trick"
Code example main.zsh:
#!/usr/bin/env zsh
. ./my_script.zsh
my_global_var=""
output=""
temp=$(my_func)
eval $(echo $temp) # become: set_vars "hello!" "my output"
Code example my_script.zsh:
#!/usr/bin/env zsh
my_func(){
echo 'my_global_var="hello!"; output="my output"' # return values
}

Variation on a Variable Variable in Bash

I am looking for a way to add a string to a variable name in bash and evaluate this as a new variable. Example:
#!/bin/bash
file="filename"
declare ${file}_info="about a file"
declare ${file}_status="status of file"
declare ${file}_number="29083451"
echo ${${file}_info} # <-- This fails with error: "bad substitution"
Is there a way to do this?
I'm not actually implementing this in any production code anywhere. I just want to know if there is some way to create a variable name using a variable and a string. It seemed like an interesting problem.
Also note that I am not asking about bash indirection, which is the use of ${!x} to evaluate the contents of a variable as a variable.
You aren't asking about indirection, but that's what can help you:
info=$file\_info
echo ${!info}

Shell script variable problem

I'm trying to write a shell script to automate a job for me. But i'm currently stuck.
Here's the problem :
I have a variable named var1 (a decreasing number from 25 to 0
and another variable named
var${var1} and this equals to some string.
then when i try to call var${var1} in anywhere in script via echo it fails.
I have tried $[var$var1], ${var$var} and many others but everytime it fails and gives the value of var1 or says operand expected error.
Thanks for your help
It's probably better if you use an array, but you can use indirection:
var25="some string"
var1=25
indirect_var="var$var1"
echo ${!indirect_var} # echoes "some string"
There's only one round of variable expansion, so you can't do it directly. You could use eval:
eval echo \${var$var1}
A better solution is to use an array:
i=5
var[$i]='foo'
echo ${var[$i]}
It sounds like you need bash variable indirection. Take a look at the link below.
http://mywiki.wooledge.org/BashFAQ/006

Resources