Register
It is currently Wed Dec 13, 2017 11:01 am

[SOLVED]A variable inside another variable


All times are UTC - 6 hours


Post new topic Reply to topic  [ 6 posts ] 
Author Message
 PostPosted: Sat Jul 30, 2016 1:10 pm   

Joined: Tue Jul 26, 2016 6:46 am
Posts: 5
I have something like
Code:
#!/bin/bash
var_2="abcd"
z=$1
echo ???var_$z???

How I can fill ??? with suitable code such that when the script acts on 2, the output be
Code:
abcd


Last edited by David on Sat Jul 30, 2016 3:08 pm, edited 1 time in total.

Top
 Profile  
 PostPosted: Sat Jul 30, 2016 1:50 pm   

Joined: Mon Oct 20, 2014 9:53 am
Posts: 560
Code:
var1="something"
another_var="var1"
echo ${!another_var}
man bash | sed -rn '/^[[:blank:]]+\$\{parameter\}/,/indirection./p'


Top
 Profile  
 PostPosted: Sat Jul 30, 2016 3:07 pm   

Joined: Tue Jul 26, 2016 6:46 am
Posts: 5
It works nice.

Thanks.


Top
 Profile  
 PostPosted: Sat Jul 30, 2016 6:22 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 638
it's not exactly what's been asked.

David asked to use script's input (in the example, 2 is given as input to the script) and rebuild variable's name ($var_<given_input>, which should rebuild $var_2, that would output abcd)

Code:
$ var_2=abcd
$ set 2
$ newVar=var_$1
$ echo ${!newVar}
abcd
or
Code:
$ unset newVar
$ declare -n newVar=var_$1
$ echo $newVar
abcd
check man bash for nameref.


Top
 Profile  
 PostPosted: Sun Jul 31, 2016 6:20 am   

Joined: Mon Oct 20, 2014 9:53 am
Posts: 560
Code:
declare -n abba
bash: declare: -n: invalid option
declare: usage: declare [-aAfFgilrtux] [-p] [name[=value] ...]


Top
 Profile  
 PostPosted: Sun Jul 31, 2016 6:42 am   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 638
Code:
/bin/bash --version
GNU bash, version 4.3.30(1)-release (x86_64-pc-linux-gnu)
bash 4.3 is now more than two years old.


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 6 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 16 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP