LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Question on variable naming and assignment... (https://www.linuxquestions.org/questions/linux-newbie-8/question-on-variable-naming-and-assignment-822140/)

${manintheyellowhat} 07-25-2010 11:38 PM

Question on variable naming and assignment...
 
can i use the value of one variable to generate a name for another variable?

for example i want to use the counter from a "do while" loop to name and define a variable each time the loop executes. for example

objectnames1=`ls -a`
objectnames2=`ls -a`
etc.

i don't have a script yet but each time through the loop i intend to cd to a particular directory and then define a variable containing a list of each object in that directory as values. for the rest of the script to work, each variable generated has to be unique, and i can't think of a good way to accomplish this.

if using a value from one variable to name another isn't possible, can anyone think of a more elegant solution? i know limited syntax but i'm willing to read up...

grail 07-26-2010 04:19 AM

Well you can probably use arrays or have a look at indirect references

i92guboj 07-26-2010 04:37 AM

I'd probably use arrays. But if you have to use them intensively I'd better use another language, like python or perl. That is, unless you have no other option.

I also suggest you to take a look at this:

http://mywiki.wooledge.org/ParsingLs

ghostdog74 07-26-2010 04:41 AM

bash has basic arrays for you. If you have bash 4.0, you can use associative arrays.
For your case
Code:

#!/bin/bash
declare -a array
array=( $(ls -a) )
echo ${array[*]}
echo ${array[0]}
echo ${array[1]}
echo ${array[2]}  #and so on

unless you are going to use these directory listing in later part of your script, otherwise, if its only a one time event, just use a for loop to go over your files (or using find etc ). No need to store them into arrays

Code:

#!/bin/bash
shopt -s nullglob
for file in *
do
  # do your stuff
done


chrism01 07-26-2010 06:27 AM

I agree arrays are probably what you need, but as per i92guboj I'd use Perl instead, judging by the brief description of your problem, and in that case, possibly hashes.
Depends exactly what the rest your requirement is...

${manintheyellowhat} 07-26-2010 06:04 PM

this being my first time shell scripting for any purpose, i didn't even know that bash had support for arrays. thanx everyone for pointing me in the right direction. did some reading... learned the syntax... problem solved.

grail 07-26-2010 07:41 PM

Quote:

problem solved
Please mark call accordingly :)


All times are GMT -5. The time now is 11:52 AM.