开发者

How can i get this value in this variable [Linux Bash]

Can i get this value in thi开发者_开发百科s variable [Linux Bash] my code

#!/bin/bash
COUNTER=1
"user$COUNTER"=text
echo "$user$COUNTER"

result : 1 i need result : text


In general, working with dynamic variable names like you want will only make your life more difficult. Arrays are much easier to work with (even in bash with it's picky syntax:

#!/bin/bash
counter=1
declare -a user   # this line is optional
user[$counter]=text
echo "${user[$counter]}"


The trick is eval

eval user$COUNTER=text

Output:

/home/shellter:>eval "user$COUNTER"=text
/home/shellter:>echo $user1
text

Eval performs variable evaluations any visible variables on the command line, and then 'resubmits' the results to normal command-line evaluation and processing.

You can see some of this happening (once you have worked with for a while it will become obvious) by turning on the shell debugging with set -vx.

I hope this helps.

P.S. as you appear to be a new user, if you get an answer that helps you please remember to mark it as accepted, and/or give it a + (or -) as a useful answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜