How to use pseudo-arrays in POSIX shell script? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election Results Why I closed the “Why is Kali so hard” questionHow can I test for POSIX compliance of shell scripts?gnuplot shell variable substitution and arraysArrays in Unix Bourne ShellPOSIX shell scripting and performance tuningWhy doesn't the last function executed in a POSIX shell script pipeline retain variable values?Using arrays in shell scriptWhen to use arrays to define commands?How can I create an arithmetic loop in a POSIX shell script?Posix shell script - Save multi line command output to variableHow to join elements of an array in POSIX delimited by a space?

Do you forfeit tax refunds/credits if you aren't required to and don't file by April 15?

If Jon Snow became King of the Seven Kingdoms what would his regnal number be?

Antler Helmet: Can it work?

What does '1 unit of lemon juice' mean in a grandma's drink recipe?

Is a manifold-with-boundary with given interior and non-empty boundary essentially unique?

How can players work together to take actions that are otherwise impossible?

Is it true that "carbohydrates are of no use for the basal metabolic need"?

If a contract sometimes uses the wrong name, is it still valid?

Output the ŋarâþ crîþ alphabet song without using (m)any letters

Does accepting a pardon have any bearing on trying that person for the same crime in a sovereign jurisdiction?

What happens to sewage if there is no river near by?

What is the musical term for a note that continously plays through a melody?

How to find all the available tools in macOS terminal?

Are my PIs rude or am I just being too sensitive?

Why is black pepper both grey and black?

I need to find the potential function of a vector field.

Is it ethical to give a final exam after the professor has quit before teaching the remaining chapters of the course?

What would be the ideal power source for a cybernetic eye?

"Seemed to had" is it correct?

Storing hydrofluoric acid before the invention of plastics

If 'B is more likely given A', then 'A is more likely given B'

How discoverable are IPv6 addresses and AAAA names by potential attackers?

ListPlot join points by nearest neighbor rather than order

Do I really need recursive chmod to restrict access to a folder?



How to use pseudo-arrays in POSIX shell script?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
2019 Community Moderator Election Results
Why I closed the “Why is Kali so hard” questionHow can I test for POSIX compliance of shell scripts?gnuplot shell variable substitution and arraysArrays in Unix Bourne ShellPOSIX shell scripting and performance tuningWhy doesn't the last function executed in a POSIX shell script pipeline retain variable values?Using arrays in shell scriptWhen to use arrays to define commands?How can I create an arithmetic loop in a POSIX shell script?Posix shell script - Save multi line command output to variableHow to join elements of an array in POSIX delimited by a space?



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








5















How to use pseudo-arrays in POSIX shell script?



I want to replace an array of 10 integers in a Bash script with something similar into POSIX shell script.



I managed to come across Rich’s sh (POSIX shell) tricks, on section Working with arrays.



What I tried:



save_pseudo_array()
sed "s/'/'\\''/g;1s/^/'/;$s/$/' \\/"
done
echo " "


coords=$(save_pseudo_array "$@")
set -- 1895 955 1104 691 1131 660 1145 570 1199 381
eval "set -- $coords"


I don't comprehend it, that's the problem, if anyone could shed some light on it, much appreciated.










share|improve this question






























    5















    How to use pseudo-arrays in POSIX shell script?



    I want to replace an array of 10 integers in a Bash script with something similar into POSIX shell script.



    I managed to come across Rich’s sh (POSIX shell) tricks, on section Working with arrays.



    What I tried:



    save_pseudo_array()
    sed "s/'/'\\''/g;1s/^/'/;$s/$/' \\/"
    done
    echo " "


    coords=$(save_pseudo_array "$@")
    set -- 1895 955 1104 691 1131 660 1145 570 1199 381
    eval "set -- $coords"


    I don't comprehend it, that's the problem, if anyone could shed some light on it, much appreciated.










    share|improve this question


























      5












      5








      5


      4






      How to use pseudo-arrays in POSIX shell script?



      I want to replace an array of 10 integers in a Bash script with something similar into POSIX shell script.



      I managed to come across Rich’s sh (POSIX shell) tricks, on section Working with arrays.



      What I tried:



      save_pseudo_array()
      sed "s/'/'\\''/g;1s/^/'/;$s/$/' \\/"
      done
      echo " "


      coords=$(save_pseudo_array "$@")
      set -- 1895 955 1104 691 1131 660 1145 570 1199 381
      eval "set -- $coords"


      I don't comprehend it, that's the problem, if anyone could shed some light on it, much appreciated.










      share|improve this question
















      How to use pseudo-arrays in POSIX shell script?



      I want to replace an array of 10 integers in a Bash script with something similar into POSIX shell script.



      I managed to come across Rich’s sh (POSIX shell) tricks, on section Working with arrays.



      What I tried:



      save_pseudo_array()
      sed "s/'/'\\''/g;1s/^/'/;$s/$/' \\/"
      done
      echo " "


      coords=$(save_pseudo_array "$@")
      set -- 1895 955 1104 691 1131 660 1145 570 1199 381
      eval "set -- $coords"


      I don't comprehend it, that's the problem, if anyone could shed some light on it, much appreciated.







      shell-script array posix






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 11 hours ago









      Rui F Ribeiro

      42.1k1483142




      42.1k1483142










      asked Feb 1 '18 at 9:06









      VlastimilVlastimil

      8,6231566149




      8,6231566149




















          2 Answers
          2






          active

          oldest

          votes


















          8














          The idea is to encode the list of arbitrary strings into a scalar variable in a format that can later be used to reconstruct the list or arbitrary strings.



           $ save_pseudo_array x "y z" $'xny' "a'b"
          'x'
          'y z'
          'x
          y'
          'a'''b'

          $


          When you stick set -- in front of that, it makes shell code that reconstructs that list of x, y z strings and stores it in the $@ array, which you just need to evaluate.



          The sed takes care of properly quoting each string (adds ' at the beginning of the first line, at the end of the last line and replaces all 's with ''').



          However, that means running one printf and sed command for each argument, so it's pretty inefficient. That could be done in a more straightforward way with just one awk invocation:



          save_pseudo_array() 
          LC_ALL=C awk -v q=' '
          BEGIN
          for (i=1; i<ARGC; i++)
          gsub(q, q "\" q q, ARGV[i])
          printf "%s ", q ARGV[i] q

          print ""
          ' "$@"






          share|improve this answer

























          • There's something to be said about portability vs efficiency here about the printf ... | sed ... vs awk, though: I don't remember all practical nuances of awk portability vs sed, but it's definitely a bigger minefield. If the target is just strictly POSIX, that might be fine, but if the target is practical portability to systems in practical use today, it might not be.

            – mtraceur
            Feb 1 '18 at 18:00











          • @mtraceur, AWK is part of POSIX and quite portable (if you avoid GNU extensions). (And I realise you’re not saying it’s not part of POSIX.)

            – Stephen Kitt
            Feb 1 '18 at 18:08







          • 1





            @mtraceur, yes basically, the problem here would be the /bin/awk of Solaris that is the one with the API from Unix V7 in the late 70s (so without -v, ARGV...). That said on Solaris, there is a POSIX awk in /usr/xpg4/bin/awk, and more generally on Solaris you know that you can't expect much from the default environment and that you need to do a PATH=$(getconf PATH):$PATH to be able to do anything.

            – Stéphane Chazelas
            Feb 1 '18 at 19:02












          • @StéphaneChazelas Is there a particular reason you are using LC_ALL=C with your awk command? I didn't think you needed to do this unless you were comparing strings with the == operator.

            – Harold Fischer
            Feb 26 at 23:02


















          8














          The basic idea is to use set to re-create the experience of working with indexed values from an array. So when you want to work with an array, you instead run set with the values; that’s



          set -- 1895 955 1104 691 1131 660 1145 570 1199 381


          Then you can use $1, $2, for etc. to work with the given values.



          All that’s not much use if you need multiple arrays though. That’s where the save and eval trick comes in: the save function processes the current positional parameters and outputs a string, with appropriate quoting, which can then be used with eval to restore the stored values. Thus you run



          coords=$(save "$@")


          to save the current working array into coords, then create a new array, work with that, and when you need to work with coords again, you eval it:



          eval "set -- $coords"


          To understand the example you have to consider that you’re working with two arrays here, the one with values set previously, and which you store in coords, and the array containing 1895, 955 etc. The snippet itself doesn’t make all that much sense on its own, you’d have some processing between the set and eval lines. If you need to return to the 1895, 955 array later, you’d save that first before restoring coords:



          newarray=$(save "$@")
          eval "set -- $coords"


          That way you can restore $newarray later.






          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%2f421158%2fhow-to-use-pseudo-arrays-in-posix-shell-script%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            8














            The idea is to encode the list of arbitrary strings into a scalar variable in a format that can later be used to reconstruct the list or arbitrary strings.



             $ save_pseudo_array x "y z" $'xny' "a'b"
            'x'
            'y z'
            'x
            y'
            'a'''b'

            $


            When you stick set -- in front of that, it makes shell code that reconstructs that list of x, y z strings and stores it in the $@ array, which you just need to evaluate.



            The sed takes care of properly quoting each string (adds ' at the beginning of the first line, at the end of the last line and replaces all 's with ''').



            However, that means running one printf and sed command for each argument, so it's pretty inefficient. That could be done in a more straightforward way with just one awk invocation:



            save_pseudo_array() 
            LC_ALL=C awk -v q=' '
            BEGIN
            for (i=1; i<ARGC; i++)
            gsub(q, q "\" q q, ARGV[i])
            printf "%s ", q ARGV[i] q

            print ""
            ' "$@"






            share|improve this answer

























            • There's something to be said about portability vs efficiency here about the printf ... | sed ... vs awk, though: I don't remember all practical nuances of awk portability vs sed, but it's definitely a bigger minefield. If the target is just strictly POSIX, that might be fine, but if the target is practical portability to systems in practical use today, it might not be.

              – mtraceur
              Feb 1 '18 at 18:00











            • @mtraceur, AWK is part of POSIX and quite portable (if you avoid GNU extensions). (And I realise you’re not saying it’s not part of POSIX.)

              – Stephen Kitt
              Feb 1 '18 at 18:08







            • 1





              @mtraceur, yes basically, the problem here would be the /bin/awk of Solaris that is the one with the API from Unix V7 in the late 70s (so without -v, ARGV...). That said on Solaris, there is a POSIX awk in /usr/xpg4/bin/awk, and more generally on Solaris you know that you can't expect much from the default environment and that you need to do a PATH=$(getconf PATH):$PATH to be able to do anything.

              – Stéphane Chazelas
              Feb 1 '18 at 19:02












            • @StéphaneChazelas Is there a particular reason you are using LC_ALL=C with your awk command? I didn't think you needed to do this unless you were comparing strings with the == operator.

              – Harold Fischer
              Feb 26 at 23:02















            8














            The idea is to encode the list of arbitrary strings into a scalar variable in a format that can later be used to reconstruct the list or arbitrary strings.



             $ save_pseudo_array x "y z" $'xny' "a'b"
            'x'
            'y z'
            'x
            y'
            'a'''b'

            $


            When you stick set -- in front of that, it makes shell code that reconstructs that list of x, y z strings and stores it in the $@ array, which you just need to evaluate.



            The sed takes care of properly quoting each string (adds ' at the beginning of the first line, at the end of the last line and replaces all 's with ''').



            However, that means running one printf and sed command for each argument, so it's pretty inefficient. That could be done in a more straightforward way with just one awk invocation:



            save_pseudo_array() 
            LC_ALL=C awk -v q=' '
            BEGIN
            for (i=1; i<ARGC; i++)
            gsub(q, q "\" q q, ARGV[i])
            printf "%s ", q ARGV[i] q

            print ""
            ' "$@"






            share|improve this answer

























            • There's something to be said about portability vs efficiency here about the printf ... | sed ... vs awk, though: I don't remember all practical nuances of awk portability vs sed, but it's definitely a bigger minefield. If the target is just strictly POSIX, that might be fine, but if the target is practical portability to systems in practical use today, it might not be.

              – mtraceur
              Feb 1 '18 at 18:00











            • @mtraceur, AWK is part of POSIX and quite portable (if you avoid GNU extensions). (And I realise you’re not saying it’s not part of POSIX.)

              – Stephen Kitt
              Feb 1 '18 at 18:08







            • 1





              @mtraceur, yes basically, the problem here would be the /bin/awk of Solaris that is the one with the API from Unix V7 in the late 70s (so without -v, ARGV...). That said on Solaris, there is a POSIX awk in /usr/xpg4/bin/awk, and more generally on Solaris you know that you can't expect much from the default environment and that you need to do a PATH=$(getconf PATH):$PATH to be able to do anything.

              – Stéphane Chazelas
              Feb 1 '18 at 19:02












            • @StéphaneChazelas Is there a particular reason you are using LC_ALL=C with your awk command? I didn't think you needed to do this unless you were comparing strings with the == operator.

              – Harold Fischer
              Feb 26 at 23:02













            8












            8








            8







            The idea is to encode the list of arbitrary strings into a scalar variable in a format that can later be used to reconstruct the list or arbitrary strings.



             $ save_pseudo_array x "y z" $'xny' "a'b"
            'x'
            'y z'
            'x
            y'
            'a'''b'

            $


            When you stick set -- in front of that, it makes shell code that reconstructs that list of x, y z strings and stores it in the $@ array, which you just need to evaluate.



            The sed takes care of properly quoting each string (adds ' at the beginning of the first line, at the end of the last line and replaces all 's with ''').



            However, that means running one printf and sed command for each argument, so it's pretty inefficient. That could be done in a more straightforward way with just one awk invocation:



            save_pseudo_array() 
            LC_ALL=C awk -v q=' '
            BEGIN
            for (i=1; i<ARGC; i++)
            gsub(q, q "\" q q, ARGV[i])
            printf "%s ", q ARGV[i] q

            print ""
            ' "$@"






            share|improve this answer















            The idea is to encode the list of arbitrary strings into a scalar variable in a format that can later be used to reconstruct the list or arbitrary strings.



             $ save_pseudo_array x "y z" $'xny' "a'b"
            'x'
            'y z'
            'x
            y'
            'a'''b'

            $


            When you stick set -- in front of that, it makes shell code that reconstructs that list of x, y z strings and stores it in the $@ array, which you just need to evaluate.



            The sed takes care of properly quoting each string (adds ' at the beginning of the first line, at the end of the last line and replaces all 's with ''').



            However, that means running one printf and sed command for each argument, so it's pretty inefficient. That could be done in a more straightforward way with just one awk invocation:



            save_pseudo_array() 
            LC_ALL=C awk -v q=' '
            BEGIN
            for (i=1; i<ARGC; i++)
            gsub(q, q "\" q q, ARGV[i])
            printf "%s ", q ARGV[i] q

            print ""
            ' "$@"







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Feb 1 '18 at 10:13

























            answered Feb 1 '18 at 9:17









            Stéphane ChazelasStéphane Chazelas

            314k57596954




            314k57596954












            • There's something to be said about portability vs efficiency here about the printf ... | sed ... vs awk, though: I don't remember all practical nuances of awk portability vs sed, but it's definitely a bigger minefield. If the target is just strictly POSIX, that might be fine, but if the target is practical portability to systems in practical use today, it might not be.

              – mtraceur
              Feb 1 '18 at 18:00











            • @mtraceur, AWK is part of POSIX and quite portable (if you avoid GNU extensions). (And I realise you’re not saying it’s not part of POSIX.)

              – Stephen Kitt
              Feb 1 '18 at 18:08







            • 1





              @mtraceur, yes basically, the problem here would be the /bin/awk of Solaris that is the one with the API from Unix V7 in the late 70s (so without -v, ARGV...). That said on Solaris, there is a POSIX awk in /usr/xpg4/bin/awk, and more generally on Solaris you know that you can't expect much from the default environment and that you need to do a PATH=$(getconf PATH):$PATH to be able to do anything.

              – Stéphane Chazelas
              Feb 1 '18 at 19:02












            • @StéphaneChazelas Is there a particular reason you are using LC_ALL=C with your awk command? I didn't think you needed to do this unless you were comparing strings with the == operator.

              – Harold Fischer
              Feb 26 at 23:02

















            • There's something to be said about portability vs efficiency here about the printf ... | sed ... vs awk, though: I don't remember all practical nuances of awk portability vs sed, but it's definitely a bigger minefield. If the target is just strictly POSIX, that might be fine, but if the target is practical portability to systems in practical use today, it might not be.

              – mtraceur
              Feb 1 '18 at 18:00











            • @mtraceur, AWK is part of POSIX and quite portable (if you avoid GNU extensions). (And I realise you’re not saying it’s not part of POSIX.)

              – Stephen Kitt
              Feb 1 '18 at 18:08







            • 1





              @mtraceur, yes basically, the problem here would be the /bin/awk of Solaris that is the one with the API from Unix V7 in the late 70s (so without -v, ARGV...). That said on Solaris, there is a POSIX awk in /usr/xpg4/bin/awk, and more generally on Solaris you know that you can't expect much from the default environment and that you need to do a PATH=$(getconf PATH):$PATH to be able to do anything.

              – Stéphane Chazelas
              Feb 1 '18 at 19:02












            • @StéphaneChazelas Is there a particular reason you are using LC_ALL=C with your awk command? I didn't think you needed to do this unless you were comparing strings with the == operator.

              – Harold Fischer
              Feb 26 at 23:02
















            There's something to be said about portability vs efficiency here about the printf ... | sed ... vs awk, though: I don't remember all practical nuances of awk portability vs sed, but it's definitely a bigger minefield. If the target is just strictly POSIX, that might be fine, but if the target is practical portability to systems in practical use today, it might not be.

            – mtraceur
            Feb 1 '18 at 18:00





            There's something to be said about portability vs efficiency here about the printf ... | sed ... vs awk, though: I don't remember all practical nuances of awk portability vs sed, but it's definitely a bigger minefield. If the target is just strictly POSIX, that might be fine, but if the target is practical portability to systems in practical use today, it might not be.

            – mtraceur
            Feb 1 '18 at 18:00













            @mtraceur, AWK is part of POSIX and quite portable (if you avoid GNU extensions). (And I realise you’re not saying it’s not part of POSIX.)

            – Stephen Kitt
            Feb 1 '18 at 18:08






            @mtraceur, AWK is part of POSIX and quite portable (if you avoid GNU extensions). (And I realise you’re not saying it’s not part of POSIX.)

            – Stephen Kitt
            Feb 1 '18 at 18:08





            1




            1





            @mtraceur, yes basically, the problem here would be the /bin/awk of Solaris that is the one with the API from Unix V7 in the late 70s (so without -v, ARGV...). That said on Solaris, there is a POSIX awk in /usr/xpg4/bin/awk, and more generally on Solaris you know that you can't expect much from the default environment and that you need to do a PATH=$(getconf PATH):$PATH to be able to do anything.

            – Stéphane Chazelas
            Feb 1 '18 at 19:02






            @mtraceur, yes basically, the problem here would be the /bin/awk of Solaris that is the one with the API from Unix V7 in the late 70s (so without -v, ARGV...). That said on Solaris, there is a POSIX awk in /usr/xpg4/bin/awk, and more generally on Solaris you know that you can't expect much from the default environment and that you need to do a PATH=$(getconf PATH):$PATH to be able to do anything.

            – Stéphane Chazelas
            Feb 1 '18 at 19:02














            @StéphaneChazelas Is there a particular reason you are using LC_ALL=C with your awk command? I didn't think you needed to do this unless you were comparing strings with the == operator.

            – Harold Fischer
            Feb 26 at 23:02





            @StéphaneChazelas Is there a particular reason you are using LC_ALL=C with your awk command? I didn't think you needed to do this unless you were comparing strings with the == operator.

            – Harold Fischer
            Feb 26 at 23:02













            8














            The basic idea is to use set to re-create the experience of working with indexed values from an array. So when you want to work with an array, you instead run set with the values; that’s



            set -- 1895 955 1104 691 1131 660 1145 570 1199 381


            Then you can use $1, $2, for etc. to work with the given values.



            All that’s not much use if you need multiple arrays though. That’s where the save and eval trick comes in: the save function processes the current positional parameters and outputs a string, with appropriate quoting, which can then be used with eval to restore the stored values. Thus you run



            coords=$(save "$@")


            to save the current working array into coords, then create a new array, work with that, and when you need to work with coords again, you eval it:



            eval "set -- $coords"


            To understand the example you have to consider that you’re working with two arrays here, the one with values set previously, and which you store in coords, and the array containing 1895, 955 etc. The snippet itself doesn’t make all that much sense on its own, you’d have some processing between the set and eval lines. If you need to return to the 1895, 955 array later, you’d save that first before restoring coords:



            newarray=$(save "$@")
            eval "set -- $coords"


            That way you can restore $newarray later.






            share|improve this answer



























              8














              The basic idea is to use set to re-create the experience of working with indexed values from an array. So when you want to work with an array, you instead run set with the values; that’s



              set -- 1895 955 1104 691 1131 660 1145 570 1199 381


              Then you can use $1, $2, for etc. to work with the given values.



              All that’s not much use if you need multiple arrays though. That’s where the save and eval trick comes in: the save function processes the current positional parameters and outputs a string, with appropriate quoting, which can then be used with eval to restore the stored values. Thus you run



              coords=$(save "$@")


              to save the current working array into coords, then create a new array, work with that, and when you need to work with coords again, you eval it:



              eval "set -- $coords"


              To understand the example you have to consider that you’re working with two arrays here, the one with values set previously, and which you store in coords, and the array containing 1895, 955 etc. The snippet itself doesn’t make all that much sense on its own, you’d have some processing between the set and eval lines. If you need to return to the 1895, 955 array later, you’d save that first before restoring coords:



              newarray=$(save "$@")
              eval "set -- $coords"


              That way you can restore $newarray later.






              share|improve this answer

























                8












                8








                8







                The basic idea is to use set to re-create the experience of working with indexed values from an array. So when you want to work with an array, you instead run set with the values; that’s



                set -- 1895 955 1104 691 1131 660 1145 570 1199 381


                Then you can use $1, $2, for etc. to work with the given values.



                All that’s not much use if you need multiple arrays though. That’s where the save and eval trick comes in: the save function processes the current positional parameters and outputs a string, with appropriate quoting, which can then be used with eval to restore the stored values. Thus you run



                coords=$(save "$@")


                to save the current working array into coords, then create a new array, work with that, and when you need to work with coords again, you eval it:



                eval "set -- $coords"


                To understand the example you have to consider that you’re working with two arrays here, the one with values set previously, and which you store in coords, and the array containing 1895, 955 etc. The snippet itself doesn’t make all that much sense on its own, you’d have some processing between the set and eval lines. If you need to return to the 1895, 955 array later, you’d save that first before restoring coords:



                newarray=$(save "$@")
                eval "set -- $coords"


                That way you can restore $newarray later.






                share|improve this answer













                The basic idea is to use set to re-create the experience of working with indexed values from an array. So when you want to work with an array, you instead run set with the values; that’s



                set -- 1895 955 1104 691 1131 660 1145 570 1199 381


                Then you can use $1, $2, for etc. to work with the given values.



                All that’s not much use if you need multiple arrays though. That’s where the save and eval trick comes in: the save function processes the current positional parameters and outputs a string, with appropriate quoting, which can then be used with eval to restore the stored values. Thus you run



                coords=$(save "$@")


                to save the current working array into coords, then create a new array, work with that, and when you need to work with coords again, you eval it:



                eval "set -- $coords"


                To understand the example you have to consider that you’re working with two arrays here, the one with values set previously, and which you store in coords, and the array containing 1895, 955 etc. The snippet itself doesn’t make all that much sense on its own, you’d have some processing between the set and eval lines. If you need to return to the 1895, 955 array later, you’d save that first before restoring coords:



                newarray=$(save "$@")
                eval "set -- $coords"


                That way you can restore $newarray later.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 1 '18 at 9:16









                Stephen KittStephen Kitt

                181k25415494




                181k25415494



























                    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%2f421158%2fhow-to-use-pseudo-arrays-in-posix-shell-script%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







                    -array, posix, shell-script

                    Popular posts from this blog

                    Mobil Contents History Mobil brands Former Mobil brands Lukoil transaction Mobil UK Mobil Australia Mobil New Zealand Mobil Greece Mobil in Japan Mobil in Canada Mobil Egypt See also References External links Navigation menuwww.mobil.com"Mobil Corporation"the original"Our Houston campus""Business & Finance: Socony-Vacuum Corp.""Popular Mechanics""Lubrite Technologies""Exxon Mobil campus 'clearly happening'""Toledo Blade - Google News Archive Search""The Lion and the Moose - How 2 Executives Pulled off the Biggest Merger Ever""ExxonMobil Press Release""Lubricants""Archived copy"the original"Mobil 1™ and Mobil Super™ motor oil and synthetic motor oil - Mobil™ Motor Oils""Mobil Delvac""Mobil Industrial website""The State of Competition in Gasoline Marketing: The Effects of Refiner Operations at Retail""Mobil Travel Guide to become Forbes Travel Guide""Hotel Rankings: Forbes Merges with Mobil"the original"Jamieson oil industry history""Mobil news""Caltex pumps for control""Watchdog blocks Caltex bid""Exxon Mobil sells service station network""Mobil Oil New Zealand Limited is New Zealand's oldest oil company, with predecessor companies having first established a presence in the country in 1896""ExxonMobil subsidiaries have a business history in New Zealand stretching back more than 120 years. We are involved in petroleum refining and distribution and the marketing of fuels, lubricants and chemical products""Archived copy"the original"Exxon Mobil to Sell Its Japanese Arm for $3.9 Billion""Gas station merger will end Esso and Mobil's long run in Japan""Esso moves to affiliate itself with PC Optimum, no longer Aeroplan, in loyalty point switch""Mobil brand of gas stations to launch in Canada after deal for 213 Loblaws-owned locations""Mobil Nears Completion of Rebranding 200 Loblaw Gas Stations""Learn about ExxonMobil's operations in Egypt""Petrol and Diesel Service Stations in Egypt - Mobil"Official websiteExxon Mobil corporate websiteMobil Industrial official websiteeeeeeeeDA04275022275790-40000 0001 0860 5061n82045453134887257134887257

                    My Life (Mary J. Blige album) Contents Background Critical reception Accolades Commercial performance Track listing Personnel Charts Certifications See also References External links Navigation menu"1. Mary J Blige, My Life - The 50 Best R&B albums of the '90s""American album certifications – Mary J. Blige – My Life""Mary J. Blige's My Life LP (1994) revisited with co-producer Chucky Thompson | Return To The Classics"the original"Key Tracks: Mary J. Blige's My Life""My Life – Mary J. Blige""Worth The Wait""My Life""Forget '411,' Mary J., Better Call 911""Spins"My Life AccoladesThe 500 Greatest Albums of All TimeTime's All-TIME 100 Albums"Top RPM Albums: Issue chartid""Dutchcharts.nl – Mary J. Blige – My Life""Mary J. Blige | Artist | Official Charts""Mary J. Blige Chart History (Billboard 200)""Mary J. Blige Chart History (Top R&B/Hip-Hop Albums)""Canadian album certifications – Mary J Blige – My Life""British album certifications – Mary J Blige – My Life""American album certifications – Mary J Blige – My Life"My LifeMy Life accoladesee

                    Frič See also Navigation menuinternal link