[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 244
  • Last Modified:

use a variable (like $i) as part of another variables name in bash

I have a file with variables like this...
server_1=
port_1=
user_1=

server_2=
port_2=
user_2=

Open in new window


I am trying to write a script that can read them in and manipulate them and write them back out.  And it should be able to handle any number of them.  Below is a simplified version of what I want to be able to do.  (i.e. not actually trying to edit anything here.  Just write it back out)

Is this at all possible?


source filewithvariables
for (( i=1; i<=$number_of_servers; i++ ))
do

echo "server_${i}=${server_${i}}" >> output 
echo "port_${i}=${port_${i}}" >> output 
echo "user_${i}=${user_${i}}" >> output 

done

Open in new window

0
Xetroximyn
Asked:
Xetroximyn
  • 3
  • 2
1 Solution
 
ozoCommented:
eval echo "server_${i}=\${server_${i}}" >> output
or
name=server_${i}; echo "server_${i}=${!name}" >> output
0
 
ozoCommented:
or
for name in ${!server_*}  ; do  echo "$name=${!name}"  ; done
0
 
XetroximynAuthor Commented:
Thanks!

Just want to understand this a bit better... I think I understand the val method.  Baiscally eval replaces the ${i} with the "1" and leaves the first $ in there because it's escaped and thus bash is left to execute
server_1=${server_1}

And I think I understand the indirect referencing with the ${!name} syntax.  It seems like it takes the contents of $name and uses that for the variable name to get the contents of instead of just getting the contents of ${!name}

However - if it worked like I think it does - I don't quite understand why these two things would not be the same

echo $name_1
i=1
echo $name_${!i}

Open in new window


any chance you can help me understand that?
0
 
ozoCommented:
i=1
echo $name_${!i}
would have the same effect as
echo $name_$1
0
 
XetroximynAuthor Commented:
TY!
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now