How to Set variables inside a Linux for loop - bash

I'm trying to determine the existing HDDs in each system using a for loop as show below, the problem is when I try to set the variable using the below code i get sda=true: command not found. What is the proper way to do this?
#!/bin/bash
for i in a b c d e f
do
grep -q sd$i /proc/partitions
if [ $? == 0 ]
then
sd$i=true
else
sd$i=false
fi
done

You need to use an array or declare:
declare sd$i=true

I would use an array in this case. For example:
$ i=a
$ sd[$i]=true
$ echo ${sd[a]}
true
As another poster stated, if you want to do this without an array, you can instead make a local variable by using syntax like declare sd$i=true. If you want to make a global variable, use export sd$i=true.

BASH FAQ entry #6: "How can I use variable variables (indirect variables, pointers, references) or associative arrays?": "Assigning indirect/reference variables"

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)

concatenate variables in a bash script

Hi I would like to set a variable by concatenating two other variables.
Example
A=1
B=2
12=C
echo $A$B
desired result being C
however the answer I get is always 12
Is it possible?
UPDATED
Example
A=X
B=Y
D=$A$B
xy=test
echo $D
desired result being "test"
It looks like you want indirect variable references.
BASH allows you to expand a parameter indirectly -- that is, one variable may contain the name of another variable:
# Bash
realvariable=contents
ref=realvariable
echo "${!ref}" # prints the contents of the real variable
But as Pieter21 indicates in his comment 12 is not a valid variable name.
Since 12 is not a valid variable name, here's an example with string variables:
> a='hello'
> b='world'
> declare my_$a_$b='my string'
> echo $my_hello_world
my string
What you are trying to do is (almost) called indirection: http://wiki.bash-hackers.org/syntax/pe#indirection
...I did some quick tests, but it does not seem logical to do this without a third variable - you cannot do concatenated indirection directly as the variables/parts being concatenated do not evaluate to the result on their own - you would have to do another evaluation. I think concatenating them first might be the easiest. That said, there is a chance you could rethink what you're doing.
Oh, and you cannot use numbers (alone or as the starting character) for variable names.
Here we go:
cake="cheese"
var1="ca"
var2="ke"
# this does not work as the indirection sees "ca" and "ke", not "cake". No output.
echo ${!var1}${!var2}
# there might be some other ways of tricking it to do this, but they don't look to sensible as indirection probably needs to work on a real variable.
# ...this works, though:
var3=${var1}${var2}
echo ${!var3}

Bash - When to use '$' in front of variables?

I'm very new to bash scripting, and as I've been searching for information online I've found a lot of seemingly contradictory advice. The thing I'm most confused about is the $ in front of variable names. My main question is, when is and isn't it appropriate to use that syntax? Thanks!
Basically, it is used when referring to the variable, but not when defining it.
When you define a variable you do not use it:
value=233
You have to use them when you call the variable:
echo "$value"
There are some exceptions to this basic rule. For example in math expresions, as etarion comments.
one more question: if I declare an array my_array and iterate through
it with a counter i, would the call to that have to be $my_array[$i]?
See the example:
$ myarray=("one" "two" "three")
$ echo ${myarray[1]} #note that the first index is 0
two
To iterate through it, this code makes it:
for item in "${myarray[#]}"
do
echo $item
done
In our case:
$ for item in "${myarray[#]}"; do echo $item; done
one
two
three
I am no bash user that knows too much. But whenever you declare variable you would not use the $, and whenever you want to call upon that variable and use its value you would use the $ sign.

How can iterate thru enumerated variables in bash?

I have a set of variables, which I obtained thru eval a file.
My variables are named with this pattern:
variable_name_1
variable_name_2
...
variable_name_n
usually those variables contain a filename, so naturally I want to iterate with in this nature:
for cur in variable_name_[i]; do
<do stuff>; done
Is there a way to achieve that functionality?
Yes, using parameter expansion:
#!/bin/bash
variable_name_1="one"
variable_name_2="two"
variable_name_3="three"
for cur in ${!variable_name_*}; do
echo "${cur}=${!cur}"
done
Example run:
$ ./foo.sh
variable_name_1=one
variable_name_2=two
variable_name_3=three
But you might want to reconsider how to obtain those variables, evaling your "config file" (?) is probably not the best choice.

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

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"

Resources