How can iterate thru enumerated variables in bash? - 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.

Related

Use a set of variables that start with the same string in bash

I know something like this is possible with DOS but I am not sure how to do it within bash.
I am writing a script that takes some configuration data: source, name, and destination. There will be a variable number of these in the configuration. I need to iterate over each set.
So, for example:
#!/bin/bash
FOLDER_1_SOURCE="/path/one"
FOLDER_1_NAME="one"
FOLDER_1_DESTINATION="one"
FOLDER_2_SOURCE="/path/two two"
FOLDER_2_NAME="two"
FOLDER_2_DESTINATION="here"
FOLDER_3_SOURCE="/something/random"
FOLDER_3_NAME="bravo"
FOLDER_3_DESTINATION="there"
FOLDER_..._SOURCE="/something/random"
FOLDER_..._NAME="bravo"
FOLDER_..._DESTINATION=""
FOLDER_X_SOURCE="/something/random"
FOLDER_X_NAME="bravo"
FOLDER_X_DESTINATION=""
Then I want to iterate over each set and get the SOURCE and NAME values for each set.
I am not stuck on this format. I just don't know how else to do this. The end goal is that I have 1 or more set of variables with source, name, and destination and then I need to iterate over them.
The answer to this type of question is nearly always "use arrays".
declare -a folder_source folder_name folder_dest
folder_source[1]="/path/one"
folder_name[1]="one"
folder_dest[1]="one"
folder_source[2]="/path/two two"
folder_name[2]="two"
folder_dest[2]="here"
folder_source[3]="/something/random"
folder_name[3]="bravo"
folder_dest[3]="there"
folder_source[4]="/something/random"
folder_name[4]="bravo"
folder_dest[4]=""
for((i=1; i<=${#folder_source[#]}; ++i)); do
echo "$i source:" "${folder_source[$i]}"
echo "$i name:" "${folder_name[$i]}"
echo "$i destination:" "${folder_dest[$i]}"
done
Demo: https://ideone.com/gZn0wH
Bash array indices are zero-based, but we just leave the zeroth slot unused here for convenience.
Tangentially, avoid upper case for your private variables.
AFIK bash does not have a facility to list all variables. A workaround - which also would mimic what is going on in DOS - is to use environment variables and restrict your search to those. In this case, you could do a
printenv|grep ^FOLDER||cut -d = -f 1
This is the same as doing in Windows CMD shell a
SET FOLDER

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}

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"

Multi layer variable substitution in shell.. possible?

I have multiple variables in a shell script; i was trying to save some code duplication and wanted to do something like following
# variables
FLAG=SIM
SIM_ICR_KEY_VAL="http://www.example.com/simi/icr"
REAL_ICR_KEY_VAL="http://www.example.com/real"
Based on the FLAG value i want to access the correct variable (without using IF's)
When i try this it echos the variable name & not the value itself.
echo $(echo ${FLAG}_ICR_KEY_VAL)
On further note; i need to use these substitutions inline in a sed statememt:
sed "s!${ISTR_KEY}=.*!${ISTR_KEY}=${SIM_ISTR_KEY_VAL}!" > tmp.file
... i am not sure its possible or not, please suggest
Reflection can be achieved with the infamous eval:
eval thisvar=\$${FLAG}_INC_KEY_VAL;
echo "We are using $thisvar"
Whenever you find yourself dynamically synthesizing a variable name, though, you are probably Doing It Wrong. You should consider alternatives like arrays:
ICR_KEY_VAL[0]="http://www.example.com/simi/icr"
ICR_KEY_VAL[1]="http://www.example.com/real"
SIM=0
echo ${ICR_KEY_VAL[$SIM]}
I don't know how to do it directly, but in bash you can do it indirectly:
FLAG=SIM
SIM_ICR_KEY_VAL="http://www.example.com/simi/icr"
REAL_ICR_KEY_VAL="http://www.example.com/real"
FLAG_ICR_KEY_VAL=${FLAG}_ICR_KEY_VAL
sed "s!${ISTR_KEY}=.*!${ISTR_KEY}=${!FLAG_ISTR_KEY_VAL}!" > tmp.file

How to Set variables inside a Linux for loop

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"

Resources