LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   concatenate strings in bash (https://www.linuxquestions.org/questions/programming-9/concatenate-strings-in-bash-923226/)

sadosan83 01-11-2012 05:57 AM

concatenate strings in bash
 
hi all

node1_pc_ip=10.20.5.10
node1_modem_ip=192.168.2.10
node2_pc_ip=10.20.5.20
node2_modem_ip=192.168.2.20



for i in $(seq "$node")
do

echo $node$i_pc_ip

done


echo $node$i_pc_ip now working , output is;
1_pc_ip
2_pc_ip
3_pc_ip
.
I would like to output is ;

10.20.5.10
10.20.5.11
10.20.5.12

help me pls

millgates 01-11-2012 07:05 AM

Hello,
1) what is seq "$node" supposed to do?
2) I'm not sure I understand what you want to do, but have you tried
Code:

eval echo \$node${i}_pc_ip
EDIT: 3) or, even better, use arrays

BenCollver 01-11-2012 07:32 AM

Or

varname="node${i}_pc_ip"
echo ${!varname}

sadosan83 01-11-2012 08:29 AM

Quote:

Originally Posted by millgates (Post 4571784)
Hello,
1) what is seq "$node" supposed to do?
2) I'm not sure I understand what you want to do, but have you tried
Code:

eval echo \$node${i}_pc_ip
EDIT: 3) or, even better, use arrays

thanks ... fixed

David the H. 01-11-2012 11:08 AM

Aargh. No, no, no! Please do not use indirect variables for things like this. And for goodness sake, stay away from eval.

As suggested, this is exactly the kind of thing you should be using arrays for.

Code:


node_pc_ip=( 10.20.5.10 10.20.5.20 )
node_modem_ip=( 192.168.2.10 192.168.2.20 )

for i in {1..2}; do

        echo "${node_pc_ip[i]}"
        echo "${node_modem_ip[i]}"

done

Please stop and take the time to read the BashGuide here, to help you understand basic scripting concepts such as arrays.

http://mywiki.wooledge.org/BashGuide


Then at least scan through the pitfalls and faq pages for more pointers and things to be aware of, such as the importance of proper quoting and using brace expansion (or a c-style loop) instead of seq:

http://mywiki.wooledge.org/BashPitfalls
http://mywiki.wooledge.org/BashFAQ

Finally, please use [code][/code] tags around your code and data, to preserve formatting and to improve readability.

Nominal Animal 01-12-2012 03:02 PM

I agree with David the H., except that since Bash uses zero-based indexing, I do believe the example snippet should read
Code:

node_pc_ip=( 10.20.5.10 10.20.5.20 )
node_modem_ip=( 192.168.2.10 192.168.2.20 )

for i in {0..1}; do

        echo "${node_pc_ip[i]}"
        echo "${node_modem_ip[i]}"

done


David the H. 01-12-2012 09:45 PM

D'oh! :doh: Thanks for catching my mistake, NA.

sadosan83 01-13-2012 01:48 AM

Quote:

Originally Posted by David the H. (Post 4573275)
D'oh! :doh: Thanks for catching my mistake, NA.

thanks all member
resolf pls :)


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