Bash - variable variables [duplicate]












32
















This question already has an answer here:




  • Dynamic variable names in Bash

    10 answers




I have the variable $foo="something" and would like to use:



bar="foo"; echo $($bar)


to get "something" echoed.










share|improve this question















marked as duplicate by codeforester bash
Users with the  bash badge can single-handedly close bash questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Feb 4 at 22:37


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 3





    Please see BashFAQ/006. Also, you shouldn't try to use a dollar sign on the left side of an assignment.

    – Dennis Williamson
    May 25 '12 at 15:56


















32
















This question already has an answer here:




  • Dynamic variable names in Bash

    10 answers




I have the variable $foo="something" and would like to use:



bar="foo"; echo $($bar)


to get "something" echoed.










share|improve this question















marked as duplicate by codeforester bash
Users with the  bash badge can single-handedly close bash questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Feb 4 at 22:37


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 3





    Please see BashFAQ/006. Also, you shouldn't try to use a dollar sign on the left side of an assignment.

    – Dennis Williamson
    May 25 '12 at 15:56
















32












32








32


12







This question already has an answer here:




  • Dynamic variable names in Bash

    10 answers




I have the variable $foo="something" and would like to use:



bar="foo"; echo $($bar)


to get "something" echoed.










share|improve this question

















This question already has an answer here:




  • Dynamic variable names in Bash

    10 answers




I have the variable $foo="something" and would like to use:



bar="foo"; echo $($bar)


to get "something" echoed.





This question already has an answer here:




  • Dynamic variable names in Bash

    10 answers








bash variables






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 25 '12 at 21:17







user1165454

















asked May 25 '12 at 15:40









user1165454user1165454

181138




181138




marked as duplicate by codeforester bash
Users with the  bash badge can single-handedly close bash questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Feb 4 at 22:37


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by codeforester bash
Users with the  bash badge can single-handedly close bash questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Feb 4 at 22:37


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 3





    Please see BashFAQ/006. Also, you shouldn't try to use a dollar sign on the left side of an assignment.

    – Dennis Williamson
    May 25 '12 at 15:56
















  • 3





    Please see BashFAQ/006. Also, you shouldn't try to use a dollar sign on the left side of an assignment.

    – Dennis Williamson
    May 25 '12 at 15:56










3




3





Please see BashFAQ/006. Also, you shouldn't try to use a dollar sign on the left side of an assignment.

– Dennis Williamson
May 25 '12 at 15:56







Please see BashFAQ/006. Also, you shouldn't try to use a dollar sign on the left side of an assignment.

– Dennis Williamson
May 25 '12 at 15:56














4 Answers
4






active

oldest

votes


















63














In bash, you can use ${!variable} to use variable variables.



foo="something"
bar="foo"
echo "${!bar}"





share|improve this answer


























  • Much better than my answer.

    – mkb
    May 25 '12 at 16:15











  • @mkb I didn't know eval :-)

    – dAm2K
    May 25 '12 at 22:28






  • 1





    in sh it says bad substitution. Any idea how to do it in sh?

    – Shiplu Mokaddim
    Sep 6 '13 at 6:00











  • how does this work with arrays?

    – Edison
    Apr 14 '14 at 21:14











  • @Edison foo1="something1" foo2="something2" bar[0]="foo1" bar[1]="foo2" echo ${!bar[0]} echo ${!bar[1]}

    – dAm2K
    Apr 14 '14 at 23:23





















7














The accepted answer is great. However, @Edison asked how to do the same for arrays. The trick is that you want your variable holding the "[@]", so that the array is expanded with the "!". Check out this function to dump variables:



$ function dump_variables() {
for var in "$@"; do
echo "$var=${!var}"
done
}
$ STRING="Hello World"
$ ARRAY=("ab" "cd")
$ dump_variables STRING ARRAY ARRAY[@]


This outputs:



STRING=Hello World
ARRAY=ab
ARRAY[@]=ab cd


When given as just ARRAY, the first element is shown as that's what's expanded by the !. By giving the ARRAY[@] format, you get the array and all its values expanded.






share|improve this answer
























  • Good point about handling arrays. Any idea how to get the indices of an array? The manual indicates this is normally done with ${!ARRAY[@]}, which seems to conflict with the variable indirection syntax.

    – dimo414
    Aug 28 '14 at 5:33











  • @dimo414 Yeah, getting the keys through indirection is trickier. You'd have to pass just the name, then do the expansion in the method: local -a 'keys=("${!'"$var"'[@]}")'. The indirection article on Bash Hackers goes into more depth.

    – bishop
    Aug 28 '14 at 13:20





















5














eval echo "$$bar" would do it.






share|improve this answer





















  • 6





    Be aware of the security implications of eval.

    – Dennis Williamson
    May 25 '12 at 15:58






  • 1





    This solution has the benefit of being POSIX-compatible for non-Bash shells (for example, lightweight environments like embedded systems or Docker containers). And you can assign the value to another variable like so: sh var=$(eval echo "$$bar")

    – Jason Suárez
    Feb 3 '17 at 4:29





















1














To make it more clear how to do it with arrays:



arr=( 'a' 'b' 'c' )
# construct a var assigning the string representation
# of the variable (array) as its value:
var=arr[@]
echo "${!var}"





share|improve this answer






























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    63














    In bash, you can use ${!variable} to use variable variables.



    foo="something"
    bar="foo"
    echo "${!bar}"





    share|improve this answer


























    • Much better than my answer.

      – mkb
      May 25 '12 at 16:15











    • @mkb I didn't know eval :-)

      – dAm2K
      May 25 '12 at 22:28






    • 1





      in sh it says bad substitution. Any idea how to do it in sh?

      – Shiplu Mokaddim
      Sep 6 '13 at 6:00











    • how does this work with arrays?

      – Edison
      Apr 14 '14 at 21:14











    • @Edison foo1="something1" foo2="something2" bar[0]="foo1" bar[1]="foo2" echo ${!bar[0]} echo ${!bar[1]}

      – dAm2K
      Apr 14 '14 at 23:23


















    63














    In bash, you can use ${!variable} to use variable variables.



    foo="something"
    bar="foo"
    echo "${!bar}"





    share|improve this answer


























    • Much better than my answer.

      – mkb
      May 25 '12 at 16:15











    • @mkb I didn't know eval :-)

      – dAm2K
      May 25 '12 at 22:28






    • 1





      in sh it says bad substitution. Any idea how to do it in sh?

      – Shiplu Mokaddim
      Sep 6 '13 at 6:00











    • how does this work with arrays?

      – Edison
      Apr 14 '14 at 21:14











    • @Edison foo1="something1" foo2="something2" bar[0]="foo1" bar[1]="foo2" echo ${!bar[0]} echo ${!bar[1]}

      – dAm2K
      Apr 14 '14 at 23:23
















    63












    63








    63







    In bash, you can use ${!variable} to use variable variables.



    foo="something"
    bar="foo"
    echo "${!bar}"





    share|improve this answer















    In bash, you can use ${!variable} to use variable variables.



    foo="something"
    bar="foo"
    echo "${!bar}"






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 26 '16 at 13:15









    Gilles

    75.5k19161205




    75.5k19161205










    answered May 25 '12 at 15:49









    dAm2KdAm2K

    7,95843039




    7,95843039













    • Much better than my answer.

      – mkb
      May 25 '12 at 16:15











    • @mkb I didn't know eval :-)

      – dAm2K
      May 25 '12 at 22:28






    • 1





      in sh it says bad substitution. Any idea how to do it in sh?

      – Shiplu Mokaddim
      Sep 6 '13 at 6:00











    • how does this work with arrays?

      – Edison
      Apr 14 '14 at 21:14











    • @Edison foo1="something1" foo2="something2" bar[0]="foo1" bar[1]="foo2" echo ${!bar[0]} echo ${!bar[1]}

      – dAm2K
      Apr 14 '14 at 23:23





















    • Much better than my answer.

      – mkb
      May 25 '12 at 16:15











    • @mkb I didn't know eval :-)

      – dAm2K
      May 25 '12 at 22:28






    • 1





      in sh it says bad substitution. Any idea how to do it in sh?

      – Shiplu Mokaddim
      Sep 6 '13 at 6:00











    • how does this work with arrays?

      – Edison
      Apr 14 '14 at 21:14











    • @Edison foo1="something1" foo2="something2" bar[0]="foo1" bar[1]="foo2" echo ${!bar[0]} echo ${!bar[1]}

      – dAm2K
      Apr 14 '14 at 23:23



















    Much better than my answer.

    – mkb
    May 25 '12 at 16:15





    Much better than my answer.

    – mkb
    May 25 '12 at 16:15













    @mkb I didn't know eval :-)

    – dAm2K
    May 25 '12 at 22:28





    @mkb I didn't know eval :-)

    – dAm2K
    May 25 '12 at 22:28




    1




    1





    in sh it says bad substitution. Any idea how to do it in sh?

    – Shiplu Mokaddim
    Sep 6 '13 at 6:00





    in sh it says bad substitution. Any idea how to do it in sh?

    – Shiplu Mokaddim
    Sep 6 '13 at 6:00













    how does this work with arrays?

    – Edison
    Apr 14 '14 at 21:14





    how does this work with arrays?

    – Edison
    Apr 14 '14 at 21:14













    @Edison foo1="something1" foo2="something2" bar[0]="foo1" bar[1]="foo2" echo ${!bar[0]} echo ${!bar[1]}

    – dAm2K
    Apr 14 '14 at 23:23







    @Edison foo1="something1" foo2="something2" bar[0]="foo1" bar[1]="foo2" echo ${!bar[0]} echo ${!bar[1]}

    – dAm2K
    Apr 14 '14 at 23:23















    7














    The accepted answer is great. However, @Edison asked how to do the same for arrays. The trick is that you want your variable holding the "[@]", so that the array is expanded with the "!". Check out this function to dump variables:



    $ function dump_variables() {
    for var in "$@"; do
    echo "$var=${!var}"
    done
    }
    $ STRING="Hello World"
    $ ARRAY=("ab" "cd")
    $ dump_variables STRING ARRAY ARRAY[@]


    This outputs:



    STRING=Hello World
    ARRAY=ab
    ARRAY[@]=ab cd


    When given as just ARRAY, the first element is shown as that's what's expanded by the !. By giving the ARRAY[@] format, you get the array and all its values expanded.






    share|improve this answer
























    • Good point about handling arrays. Any idea how to get the indices of an array? The manual indicates this is normally done with ${!ARRAY[@]}, which seems to conflict with the variable indirection syntax.

      – dimo414
      Aug 28 '14 at 5:33











    • @dimo414 Yeah, getting the keys through indirection is trickier. You'd have to pass just the name, then do the expansion in the method: local -a 'keys=("${!'"$var"'[@]}")'. The indirection article on Bash Hackers goes into more depth.

      – bishop
      Aug 28 '14 at 13:20


















    7














    The accepted answer is great. However, @Edison asked how to do the same for arrays. The trick is that you want your variable holding the "[@]", so that the array is expanded with the "!". Check out this function to dump variables:



    $ function dump_variables() {
    for var in "$@"; do
    echo "$var=${!var}"
    done
    }
    $ STRING="Hello World"
    $ ARRAY=("ab" "cd")
    $ dump_variables STRING ARRAY ARRAY[@]


    This outputs:



    STRING=Hello World
    ARRAY=ab
    ARRAY[@]=ab cd


    When given as just ARRAY, the first element is shown as that's what's expanded by the !. By giving the ARRAY[@] format, you get the array and all its values expanded.






    share|improve this answer
























    • Good point about handling arrays. Any idea how to get the indices of an array? The manual indicates this is normally done with ${!ARRAY[@]}, which seems to conflict with the variable indirection syntax.

      – dimo414
      Aug 28 '14 at 5:33











    • @dimo414 Yeah, getting the keys through indirection is trickier. You'd have to pass just the name, then do the expansion in the method: local -a 'keys=("${!'"$var"'[@]}")'. The indirection article on Bash Hackers goes into more depth.

      – bishop
      Aug 28 '14 at 13:20
















    7












    7








    7







    The accepted answer is great. However, @Edison asked how to do the same for arrays. The trick is that you want your variable holding the "[@]", so that the array is expanded with the "!". Check out this function to dump variables:



    $ function dump_variables() {
    for var in "$@"; do
    echo "$var=${!var}"
    done
    }
    $ STRING="Hello World"
    $ ARRAY=("ab" "cd")
    $ dump_variables STRING ARRAY ARRAY[@]


    This outputs:



    STRING=Hello World
    ARRAY=ab
    ARRAY[@]=ab cd


    When given as just ARRAY, the first element is shown as that's what's expanded by the !. By giving the ARRAY[@] format, you get the array and all its values expanded.






    share|improve this answer













    The accepted answer is great. However, @Edison asked how to do the same for arrays. The trick is that you want your variable holding the "[@]", so that the array is expanded with the "!". Check out this function to dump variables:



    $ function dump_variables() {
    for var in "$@"; do
    echo "$var=${!var}"
    done
    }
    $ STRING="Hello World"
    $ ARRAY=("ab" "cd")
    $ dump_variables STRING ARRAY ARRAY[@]


    This outputs:



    STRING=Hello World
    ARRAY=ab
    ARRAY[@]=ab cd


    When given as just ARRAY, the first element is shown as that's what's expanded by the !. By giving the ARRAY[@] format, you get the array and all its values expanded.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Aug 6 '14 at 18:10









    bishopbishop

    24.5k56790




    24.5k56790













    • Good point about handling arrays. Any idea how to get the indices of an array? The manual indicates this is normally done with ${!ARRAY[@]}, which seems to conflict with the variable indirection syntax.

      – dimo414
      Aug 28 '14 at 5:33











    • @dimo414 Yeah, getting the keys through indirection is trickier. You'd have to pass just the name, then do the expansion in the method: local -a 'keys=("${!'"$var"'[@]}")'. The indirection article on Bash Hackers goes into more depth.

      – bishop
      Aug 28 '14 at 13:20





















    • Good point about handling arrays. Any idea how to get the indices of an array? The manual indicates this is normally done with ${!ARRAY[@]}, which seems to conflict with the variable indirection syntax.

      – dimo414
      Aug 28 '14 at 5:33











    • @dimo414 Yeah, getting the keys through indirection is trickier. You'd have to pass just the name, then do the expansion in the method: local -a 'keys=("${!'"$var"'[@]}")'. The indirection article on Bash Hackers goes into more depth.

      – bishop
      Aug 28 '14 at 13:20



















    Good point about handling arrays. Any idea how to get the indices of an array? The manual indicates this is normally done with ${!ARRAY[@]}, which seems to conflict with the variable indirection syntax.

    – dimo414
    Aug 28 '14 at 5:33





    Good point about handling arrays. Any idea how to get the indices of an array? The manual indicates this is normally done with ${!ARRAY[@]}, which seems to conflict with the variable indirection syntax.

    – dimo414
    Aug 28 '14 at 5:33













    @dimo414 Yeah, getting the keys through indirection is trickier. You'd have to pass just the name, then do the expansion in the method: local -a 'keys=("${!'"$var"'[@]}")'. The indirection article on Bash Hackers goes into more depth.

    – bishop
    Aug 28 '14 at 13:20







    @dimo414 Yeah, getting the keys through indirection is trickier. You'd have to pass just the name, then do the expansion in the method: local -a 'keys=("${!'"$var"'[@]}")'. The indirection article on Bash Hackers goes into more depth.

    – bishop
    Aug 28 '14 at 13:20













    5














    eval echo "$$bar" would do it.






    share|improve this answer





















    • 6





      Be aware of the security implications of eval.

      – Dennis Williamson
      May 25 '12 at 15:58






    • 1





      This solution has the benefit of being POSIX-compatible for non-Bash shells (for example, lightweight environments like embedded systems or Docker containers). And you can assign the value to another variable like so: sh var=$(eval echo "$$bar")

      – Jason Suárez
      Feb 3 '17 at 4:29


















    5














    eval echo "$$bar" would do it.






    share|improve this answer





















    • 6





      Be aware of the security implications of eval.

      – Dennis Williamson
      May 25 '12 at 15:58






    • 1





      This solution has the benefit of being POSIX-compatible for non-Bash shells (for example, lightweight environments like embedded systems or Docker containers). And you can assign the value to another variable like so: sh var=$(eval echo "$$bar")

      – Jason Suárez
      Feb 3 '17 at 4:29
















    5












    5








    5







    eval echo "$$bar" would do it.






    share|improve this answer















    eval echo "$$bar" would do it.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 26 '16 at 13:16









    Gilles

    75.5k19161205




    75.5k19161205










    answered May 25 '12 at 15:44









    mkbmkb

    11k12246




    11k12246








    • 6





      Be aware of the security implications of eval.

      – Dennis Williamson
      May 25 '12 at 15:58






    • 1





      This solution has the benefit of being POSIX-compatible for non-Bash shells (for example, lightweight environments like embedded systems or Docker containers). And you can assign the value to another variable like so: sh var=$(eval echo "$$bar")

      – Jason Suárez
      Feb 3 '17 at 4:29
















    • 6





      Be aware of the security implications of eval.

      – Dennis Williamson
      May 25 '12 at 15:58






    • 1





      This solution has the benefit of being POSIX-compatible for non-Bash shells (for example, lightweight environments like embedded systems or Docker containers). And you can assign the value to another variable like so: sh var=$(eval echo "$$bar")

      – Jason Suárez
      Feb 3 '17 at 4:29










    6




    6





    Be aware of the security implications of eval.

    – Dennis Williamson
    May 25 '12 at 15:58





    Be aware of the security implications of eval.

    – Dennis Williamson
    May 25 '12 at 15:58




    1




    1





    This solution has the benefit of being POSIX-compatible for non-Bash shells (for example, lightweight environments like embedded systems or Docker containers). And you can assign the value to another variable like so: sh var=$(eval echo "$$bar")

    – Jason Suárez
    Feb 3 '17 at 4:29







    This solution has the benefit of being POSIX-compatible for non-Bash shells (for example, lightweight environments like embedded systems or Docker containers). And you can assign the value to another variable like so: sh var=$(eval echo "$$bar")

    – Jason Suárez
    Feb 3 '17 at 4:29













    1














    To make it more clear how to do it with arrays:



    arr=( 'a' 'b' 'c' )
    # construct a var assigning the string representation
    # of the variable (array) as its value:
    var=arr[@]
    echo "${!var}"





    share|improve this answer




























      1














      To make it more clear how to do it with arrays:



      arr=( 'a' 'b' 'c' )
      # construct a var assigning the string representation
      # of the variable (array) as its value:
      var=arr[@]
      echo "${!var}"





      share|improve this answer


























        1












        1








        1







        To make it more clear how to do it with arrays:



        arr=( 'a' 'b' 'c' )
        # construct a var assigning the string representation
        # of the variable (array) as its value:
        var=arr[@]
        echo "${!var}"





        share|improve this answer













        To make it more clear how to do it with arrays:



        arr=( 'a' 'b' 'c' )
        # construct a var assigning the string representation
        # of the variable (array) as its value:
        var=arr[@]
        echo "${!var}"






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered May 16 '16 at 5:56









        JahidJahid

        13.7k46084




        13.7k46084















            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas