Assign the same string to multiple variablesVariable name from command outputSharing variables across multiple shell scriptsReplace string in a file with another where both are saved in variablesPassing multiple of arguments with whitespaces through a script to sshHow to assign variables associated with list of ranges to another table with integersCut the string in half with the last specific character shows up in the stringIn bash, how to delay interpolation of a variable that has a dynamic variable within its stringHow can I evaluate bash arguments in a string once variables have changedCreating n variables in Bash without assigning them one by one?Escaping a string for a parameter inside a script

Question about exercise 11.5 in TeXbook

Transform the partial differential equation with new independent variables

How do Russian speakers idiomatically express the idea of "Ce n’est pas donné à tout le monde de ..." in French?

Can non-English-speaking characters use wordplay specific to English?

Is a post-climate apocolypse city in which many or most insects have disappeared realistic?

If a massive object like Jupiter flew past the Earth how close would it need to come to pull people off of the surface?

Crossword gone overboard

Can a wire having a 610-670 THz (frequency of blue light) AC frequency supply, generate blue light?

Crossing US border with music files I'm legally allowed to possess

Could I be denied entry into Ireland due to medical and police situations during a previous UK visit?

File globbing pattern, !(*example), behaves differently in bash script than it does in bash shell

Can a non-EU citizen travel within schengen zone freely without passport?

Yandex Programming Contest: Alarms

Black-and-white film where monster/alien gets fried

What are the problems in teaching guitar via Skype?

Smart people send dumb people to a new planet on a space craft that crashes into a body of water

Why colon to denote that a value belongs to a type?

Mother abusing my finances

How could Catholicism have incorporated witchcraft into its dogma?

Tic-Tac-Toe for the terminal

How do I subvert the tropes of a train heist?

Why does the 6502 have the BIT instruction?

Is CD audio quality good enough for the final delivery of music?

How does apt-get work, in detail?



Assign the same string to multiple variables


Variable name from command outputSharing variables across multiple shell scriptsReplace string in a file with another where both are saved in variablesPassing multiple of arguments with whitespaces through a script to sshHow to assign variables associated with list of ranges to another table with integersCut the string in half with the last specific character shows up in the stringIn bash, how to delay interpolation of a variable that has a dynamic variable within its stringHow can I evaluate bash arguments in a string once variables have changedCreating n variables in Bash without assigning them one by one?Escaping a string for a parameter inside a script






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








5















I want to assign the string contained in $value to multiple variables.



Actually the example I gave before (var1=var2=...=$value) was not reflecting exactly what I wanted.
So far, I found this but it only works if $value is an integer:



$ let varT=varz=var3=$value


How can I do that?










share|improve this question



















  • 1





    Shouldn't the question be: Assign the same string value to multiple variables? (subject and object switched)?

    – rexkogitans
    May 15 at 9:30

















5















I want to assign the string contained in $value to multiple variables.



Actually the example I gave before (var1=var2=...=$value) was not reflecting exactly what I wanted.
So far, I found this but it only works if $value is an integer:



$ let varT=varz=var3=$value


How can I do that?










share|improve this question



















  • 1





    Shouldn't the question be: Assign the same string value to multiple variables? (subject and object switched)?

    – rexkogitans
    May 15 at 9:30













5












5








5


2






I want to assign the string contained in $value to multiple variables.



Actually the example I gave before (var1=var2=...=$value) was not reflecting exactly what I wanted.
So far, I found this but it only works if $value is an integer:



$ let varT=varz=var3=$value


How can I do that?










share|improve this question
















I want to assign the string contained in $value to multiple variables.



Actually the example I gave before (var1=var2=...=$value) was not reflecting exactly what I wanted.
So far, I found this but it only works if $value is an integer:



$ let varT=varz=var3=$value


How can I do that?







bash assignment






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 15 at 9:39









muru

38.4k592168




38.4k592168










asked May 15 at 7:06









SebMaSebMa

3351413




3351413







  • 1





    Shouldn't the question be: Assign the same string value to multiple variables? (subject and object switched)?

    – rexkogitans
    May 15 at 9:30












  • 1





    Shouldn't the question be: Assign the same string value to multiple variables? (subject and object switched)?

    – rexkogitans
    May 15 at 9:30







1




1





Shouldn't the question be: Assign the same string value to multiple variables? (subject and object switched)?

– rexkogitans
May 15 at 9:30





Shouldn't the question be: Assign the same string value to multiple variables? (subject and object switched)?

– rexkogitans
May 15 at 9:30










4 Answers
4






active

oldest

votes


















6














In my opinion you're better of just doing the more readable:



var1="$value" var2="$value" var3="$value" var4="$value" var5="$value" var6="$value" var7="$value" var8="$value" var9="$value" var10="$value"


But if you want a very short way of accomplishing this then try:



declare var1..10="$value"


Edited: using brace expansions instead of printf and declare instead of eval, which could be dangerous depending on what's in $value.



Cf. EDIT1: You could still use brace expansions in the new case:



declare varT,z,3="$value"


It's safer than the printf approach in the comments because it can handle spaces in $value.






share|improve this answer

























  • Please see my EDIT1. The printf method you gave was just fine if you put the declare in front : declare $(printf .....)

    – SebMa
    May 15 at 7:56











  • With EDIT1 using printf that would be: declare $(printf "var%s=$value " T z 3). But be careful with spaces in $value.

    – laenkeio
    May 15 at 8:04











  • Note that the declare approach is still dangerous if any of the variables were previously declared as arrays. Try after var3=() value='([0$(echo Gotcha>&2)]=)'

    – Stéphane Chazelas
    May 15 at 12:01












  • eval is fine if used as eval var1..10=$value, that is as long as the (arbitrary) content of $value is not evaluated as shell code.

    – Stéphane Chazelas
    May 15 at 12:19


















6














let is doing an arithmetic evaluation. In bash, this is equivalent to (( ... )). This is why your code only works for integers.



Using an array instead of specially named variables:



var=( "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" )

printf 'var[5]=%sn' "$var[5]"


or an associative array,



declare -A var

var=( ["T"]=$value ["z"]=$value [3]=$value )

printf 'var[T]=%sn' "$var["T"]"


You could also do a loop:



for varname in var0 var1 varT varfoo; do
declare -n var="$varname"
var=$value
done


This loop loops over names of variables. In the loop body, a name reference variable is created that references the current loop variable. When the value of the name reference variable is set, the named variable is set.






share|improve this answer

























  • What does the -n option do? I get an error with it. Ah... namerefs (>= 4.3, IIRC?)

    – muru
    May 15 at 8:08







  • 1





    @muru Yes, declare -n creates a name reference variable. You would have to run bash 4.3+ to use name references.

    – Kusalananda
    May 15 at 8:09



















3














value=balabala
eval var1..10=$value
echo $var1..10





share|improve this answer
































    2














    Value='-%% this is a test %%-'
    for VarName in myVar1 myVar2 myOtherVar; do printf -v "$VarName" %s "$Value"; done





    share|improve this answer

























      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "106"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f519013%2fassign-the-same-string-to-multiple-variables%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      6














      In my opinion you're better of just doing the more readable:



      var1="$value" var2="$value" var3="$value" var4="$value" var5="$value" var6="$value" var7="$value" var8="$value" var9="$value" var10="$value"


      But if you want a very short way of accomplishing this then try:



      declare var1..10="$value"


      Edited: using brace expansions instead of printf and declare instead of eval, which could be dangerous depending on what's in $value.



      Cf. EDIT1: You could still use brace expansions in the new case:



      declare varT,z,3="$value"


      It's safer than the printf approach in the comments because it can handle spaces in $value.






      share|improve this answer

























      • Please see my EDIT1. The printf method you gave was just fine if you put the declare in front : declare $(printf .....)

        – SebMa
        May 15 at 7:56











      • With EDIT1 using printf that would be: declare $(printf "var%s=$value " T z 3). But be careful with spaces in $value.

        – laenkeio
        May 15 at 8:04











      • Note that the declare approach is still dangerous if any of the variables were previously declared as arrays. Try after var3=() value='([0$(echo Gotcha>&2)]=)'

        – Stéphane Chazelas
        May 15 at 12:01












      • eval is fine if used as eval var1..10=$value, that is as long as the (arbitrary) content of $value is not evaluated as shell code.

        – Stéphane Chazelas
        May 15 at 12:19















      6














      In my opinion you're better of just doing the more readable:



      var1="$value" var2="$value" var3="$value" var4="$value" var5="$value" var6="$value" var7="$value" var8="$value" var9="$value" var10="$value"


      But if you want a very short way of accomplishing this then try:



      declare var1..10="$value"


      Edited: using brace expansions instead of printf and declare instead of eval, which could be dangerous depending on what's in $value.



      Cf. EDIT1: You could still use brace expansions in the new case:



      declare varT,z,3="$value"


      It's safer than the printf approach in the comments because it can handle spaces in $value.






      share|improve this answer

























      • Please see my EDIT1. The printf method you gave was just fine if you put the declare in front : declare $(printf .....)

        – SebMa
        May 15 at 7:56











      • With EDIT1 using printf that would be: declare $(printf "var%s=$value " T z 3). But be careful with spaces in $value.

        – laenkeio
        May 15 at 8:04











      • Note that the declare approach is still dangerous if any of the variables were previously declared as arrays. Try after var3=() value='([0$(echo Gotcha>&2)]=)'

        – Stéphane Chazelas
        May 15 at 12:01












      • eval is fine if used as eval var1..10=$value, that is as long as the (arbitrary) content of $value is not evaluated as shell code.

        – Stéphane Chazelas
        May 15 at 12:19













      6












      6








      6







      In my opinion you're better of just doing the more readable:



      var1="$value" var2="$value" var3="$value" var4="$value" var5="$value" var6="$value" var7="$value" var8="$value" var9="$value" var10="$value"


      But if you want a very short way of accomplishing this then try:



      declare var1..10="$value"


      Edited: using brace expansions instead of printf and declare instead of eval, which could be dangerous depending on what's in $value.



      Cf. EDIT1: You could still use brace expansions in the new case:



      declare varT,z,3="$value"


      It's safer than the printf approach in the comments because it can handle spaces in $value.






      share|improve this answer















      In my opinion you're better of just doing the more readable:



      var1="$value" var2="$value" var3="$value" var4="$value" var5="$value" var6="$value" var7="$value" var8="$value" var9="$value" var10="$value"


      But if you want a very short way of accomplishing this then try:



      declare var1..10="$value"


      Edited: using brace expansions instead of printf and declare instead of eval, which could be dangerous depending on what's in $value.



      Cf. EDIT1: You could still use brace expansions in the new case:



      declare varT,z,3="$value"


      It's safer than the printf approach in the comments because it can handle spaces in $value.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited May 15 at 8:08

























      answered May 15 at 7:30









      laenkeiolaenkeio

      4617




      4617












      • Please see my EDIT1. The printf method you gave was just fine if you put the declare in front : declare $(printf .....)

        – SebMa
        May 15 at 7:56











      • With EDIT1 using printf that would be: declare $(printf "var%s=$value " T z 3). But be careful with spaces in $value.

        – laenkeio
        May 15 at 8:04











      • Note that the declare approach is still dangerous if any of the variables were previously declared as arrays. Try after var3=() value='([0$(echo Gotcha>&2)]=)'

        – Stéphane Chazelas
        May 15 at 12:01












      • eval is fine if used as eval var1..10=$value, that is as long as the (arbitrary) content of $value is not evaluated as shell code.

        – Stéphane Chazelas
        May 15 at 12:19

















      • Please see my EDIT1. The printf method you gave was just fine if you put the declare in front : declare $(printf .....)

        – SebMa
        May 15 at 7:56











      • With EDIT1 using printf that would be: declare $(printf "var%s=$value " T z 3). But be careful with spaces in $value.

        – laenkeio
        May 15 at 8:04











      • Note that the declare approach is still dangerous if any of the variables were previously declared as arrays. Try after var3=() value='([0$(echo Gotcha>&2)]=)'

        – Stéphane Chazelas
        May 15 at 12:01












      • eval is fine if used as eval var1..10=$value, that is as long as the (arbitrary) content of $value is not evaluated as shell code.

        – Stéphane Chazelas
        May 15 at 12:19
















      Please see my EDIT1. The printf method you gave was just fine if you put the declare in front : declare $(printf .....)

      – SebMa
      May 15 at 7:56





      Please see my EDIT1. The printf method you gave was just fine if you put the declare in front : declare $(printf .....)

      – SebMa
      May 15 at 7:56













      With EDIT1 using printf that would be: declare $(printf "var%s=$value " T z 3). But be careful with spaces in $value.

      – laenkeio
      May 15 at 8:04





      With EDIT1 using printf that would be: declare $(printf "var%s=$value " T z 3). But be careful with spaces in $value.

      – laenkeio
      May 15 at 8:04













      Note that the declare approach is still dangerous if any of the variables were previously declared as arrays. Try after var3=() value='([0$(echo Gotcha>&2)]=)'

      – Stéphane Chazelas
      May 15 at 12:01






      Note that the declare approach is still dangerous if any of the variables were previously declared as arrays. Try after var3=() value='([0$(echo Gotcha>&2)]=)'

      – Stéphane Chazelas
      May 15 at 12:01














      eval is fine if used as eval var1..10=$value, that is as long as the (arbitrary) content of $value is not evaluated as shell code.

      – Stéphane Chazelas
      May 15 at 12:19





      eval is fine if used as eval var1..10=$value, that is as long as the (arbitrary) content of $value is not evaluated as shell code.

      – Stéphane Chazelas
      May 15 at 12:19













      6














      let is doing an arithmetic evaluation. In bash, this is equivalent to (( ... )). This is why your code only works for integers.



      Using an array instead of specially named variables:



      var=( "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" )

      printf 'var[5]=%sn' "$var[5]"


      or an associative array,



      declare -A var

      var=( ["T"]=$value ["z"]=$value [3]=$value )

      printf 'var[T]=%sn' "$var["T"]"


      You could also do a loop:



      for varname in var0 var1 varT varfoo; do
      declare -n var="$varname"
      var=$value
      done


      This loop loops over names of variables. In the loop body, a name reference variable is created that references the current loop variable. When the value of the name reference variable is set, the named variable is set.






      share|improve this answer

























      • What does the -n option do? I get an error with it. Ah... namerefs (>= 4.3, IIRC?)

        – muru
        May 15 at 8:08







      • 1





        @muru Yes, declare -n creates a name reference variable. You would have to run bash 4.3+ to use name references.

        – Kusalananda
        May 15 at 8:09
















      6














      let is doing an arithmetic evaluation. In bash, this is equivalent to (( ... )). This is why your code only works for integers.



      Using an array instead of specially named variables:



      var=( "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" )

      printf 'var[5]=%sn' "$var[5]"


      or an associative array,



      declare -A var

      var=( ["T"]=$value ["z"]=$value [3]=$value )

      printf 'var[T]=%sn' "$var["T"]"


      You could also do a loop:



      for varname in var0 var1 varT varfoo; do
      declare -n var="$varname"
      var=$value
      done


      This loop loops over names of variables. In the loop body, a name reference variable is created that references the current loop variable. When the value of the name reference variable is set, the named variable is set.






      share|improve this answer

























      • What does the -n option do? I get an error with it. Ah... namerefs (>= 4.3, IIRC?)

        – muru
        May 15 at 8:08







      • 1





        @muru Yes, declare -n creates a name reference variable. You would have to run bash 4.3+ to use name references.

        – Kusalananda
        May 15 at 8:09














      6












      6








      6







      let is doing an arithmetic evaluation. In bash, this is equivalent to (( ... )). This is why your code only works for integers.



      Using an array instead of specially named variables:



      var=( "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" )

      printf 'var[5]=%sn' "$var[5]"


      or an associative array,



      declare -A var

      var=( ["T"]=$value ["z"]=$value [3]=$value )

      printf 'var[T]=%sn' "$var["T"]"


      You could also do a loop:



      for varname in var0 var1 varT varfoo; do
      declare -n var="$varname"
      var=$value
      done


      This loop loops over names of variables. In the loop body, a name reference variable is created that references the current loop variable. When the value of the name reference variable is set, the named variable is set.






      share|improve this answer















      let is doing an arithmetic evaluation. In bash, this is equivalent to (( ... )). This is why your code only works for integers.



      Using an array instead of specially named variables:



      var=( "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" )

      printf 'var[5]=%sn' "$var[5]"


      or an associative array,



      declare -A var

      var=( ["T"]=$value ["z"]=$value [3]=$value )

      printf 'var[T]=%sn' "$var["T"]"


      You could also do a loop:



      for varname in var0 var1 varT varfoo; do
      declare -n var="$varname"
      var=$value
      done


      This loop loops over names of variables. In the loop body, a name reference variable is created that references the current loop variable. When the value of the name reference variable is set, the named variable is set.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited May 15 at 8:07

























      answered May 15 at 7:50









      KusalanandaKusalananda

      148k18279467




      148k18279467












      • What does the -n option do? I get an error with it. Ah... namerefs (>= 4.3, IIRC?)

        – muru
        May 15 at 8:08







      • 1





        @muru Yes, declare -n creates a name reference variable. You would have to run bash 4.3+ to use name references.

        – Kusalananda
        May 15 at 8:09


















      • What does the -n option do? I get an error with it. Ah... namerefs (>= 4.3, IIRC?)

        – muru
        May 15 at 8:08







      • 1





        @muru Yes, declare -n creates a name reference variable. You would have to run bash 4.3+ to use name references.

        – Kusalananda
        May 15 at 8:09

















      What does the -n option do? I get an error with it. Ah... namerefs (>= 4.3, IIRC?)

      – muru
      May 15 at 8:08






      What does the -n option do? I get an error with it. Ah... namerefs (>= 4.3, IIRC?)

      – muru
      May 15 at 8:08





      1




      1





      @muru Yes, declare -n creates a name reference variable. You would have to run bash 4.3+ to use name references.

      – Kusalananda
      May 15 at 8:09






      @muru Yes, declare -n creates a name reference variable. You would have to run bash 4.3+ to use name references.

      – Kusalananda
      May 15 at 8:09












      3














      value=balabala
      eval var1..10=$value
      echo $var1..10





      share|improve this answer





























        3














        value=balabala
        eval var1..10=$value
        echo $var1..10





        share|improve this answer



























          3












          3








          3







          value=balabala
          eval var1..10=$value
          echo $var1..10





          share|improve this answer















          value=balabala
          eval var1..10=$value
          echo $var1..10






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 15 at 12:16









          Stéphane Chazelas

          320k57606976




          320k57606976










          answered May 15 at 7:39









          dedowsdidedowsdi

          70416




          70416





















              2














              Value='-%% this is a test %%-'
              for VarName in myVar1 myVar2 myOtherVar; do printf -v "$VarName" %s "$Value"; done





              share|improve this answer





























                2














                Value='-%% this is a test %%-'
                for VarName in myVar1 myVar2 myOtherVar; do printf -v "$VarName" %s "$Value"; done





                share|improve this answer



























                  2












                  2








                  2







                  Value='-%% this is a test %%-'
                  for VarName in myVar1 myVar2 myOtherVar; do printf -v "$VarName" %s "$Value"; done





                  share|improve this answer















                  Value='-%% this is a test %%-'
                  for VarName in myVar1 myVar2 myOtherVar; do printf -v "$VarName" %s "$Value"; done






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited May 15 at 12:20









                  Stéphane Chazelas

                  320k57606976




                  320k57606976










                  answered May 15 at 11:08









                  BuygrushBuygrush

                  211




                  211



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Unix & Linux Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f519013%2fassign-the-same-string-to-multiple-variables%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

                      Bruxelas-Capital Índice Historia | Composición | Situación lingüística | Clima | Cidades irmandadas | Notas | Véxase tamén | Menú de navegacióneO uso das linguas en Bruxelas e a situación do neerlandés"Rexión de Bruxelas Capital"o orixinalSitio da rexiónPáxina de Bruselas no sitio da Oficina de Promoción Turística de Valonia e BruxelasMapa Interactivo da Rexión de Bruxelas-CapitaleeWorldCat332144929079854441105155190212ID28008674080552-90000 0001 0666 3698n94104302ID540940339365017018237

                      What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company