You are not logged in.

#1 2009-10-09 16:20:08

Gen2ly
Member
From: Sevierville, TN
Registered: 2009-03-06
Posts: 1,529
Website

[Solved] Wildcard possible in variable for a loop?

Perhaps it just me being lazy but I'm writing a script I need to put in a loop that will have a good number of variables in it.  I'd like to be able to make one variable with a wildcard to simplify things.  For example, I'd like to do:

tst1=hello
tst2=hi
tst3=howdy

for var in $tst*; do
  echo "$var"
done

Is there a way to do this?

Last edited by Gen2ly (2009-10-09 21:35:26)


Setting Up a Scripting Environment | Proud donor to wikipedia - link

Offline

#2 2009-10-09 17:25:23

scragar
Member
Registered: 2009-07-14
Posts: 108

Re: [Solved] Wildcard possible in variable for a loop?

tst=(hello hi howdy)
for var in ${tst[@]}; do
  echo "$var"
done

Or you could write:

tst[0]='hello'
tst[1]='hi'
tst[2]='howdy'

for var in ${tst[@]}; do
  echo "$var"
done

tongue

Last edited by scragar (2009-10-09 17:26:30)

Offline

#3 2009-10-09 20:09:29

Gen2ly
Member
From: Sevierville, TN
Registered: 2009-03-06
Posts: 1,529
Website

Re: [Solved] Wildcard possible in variable for a loop?

Thanks for the help, scragar.  Is it possible to do this with variables?  For example, I'm trying to do this:

#!/bin/bash

# github repositories
gitrepos=(home bash blah)

# local repositories
for repos in ${gitrepos[@]}; do
  loc$repos=$HOME/.github-$repos
done

echo "$lochome $locbash $locblah"

Setting Up a Scripting Environment | Proud donor to wikipedia - link

Offline

#4 2009-10-09 20:56:52

scragar
Member
Registered: 2009-07-14
Posts: 108

Re: [Solved] Wildcard possible in variable for a loop?

I don't think so other than using eval:

#!/bin/bash

# github repositories
gitrepos=(home bash blah)

# local repositories
for repos in ${gitrepos[@]}; do
  eval "\$loc$repos=\"\$HOME/.github-\$repos\""
done

echo "$lochome $locbash $locblah"

Offline

#5 2009-10-09 21:23:15

Gen2ly
Member
From: Sevierville, TN
Registered: 2009-03-06
Posts: 1,529
Website

Re: [Solved] Wildcard possible in variable for a loop?

Ah, yes, that did it.  Nice.  I've never used eval before though I understand it evaluates the command twice.  Why it didn't evaluate it the first time is something I got to learn still.

Thanks for the help, scragar.

Last edited by Gen2ly (2009-10-09 21:35:05)


Setting Up a Scripting Environment | Proud donor to wikipedia - link

Offline

Board footer

Powered by FluxBB