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

                    Frič See also Navigation menuinternal link

                    Identify plant with long narrow paired leaves and reddish stems Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?What is this plant with long sharp leaves? Is it a weed?What is this 3ft high, stalky plant, with mid sized narrow leaves?What is this young shrub with opposite ovate, crenate leaves and reddish stems?What is this plant with large broad serrated leaves?Identify this upright branching weed with long leaves and reddish stemsPlease help me identify this bulbous plant with long, broad leaves and white flowersWhat is this small annual with narrow gray/green leaves and rust colored daisy-type flowers?What is this chilli plant?Does anyone know what type of chilli plant this is?Help identify this plant

                    fontconfig warning: “/etc/fonts/fonts.conf”, line 100: unknown “element blank” The 2019 Stack Overflow Developer Survey Results Are In“tar: unrecognized option --warning” during 'apt-get install'How to fix Fontconfig errorHow do I figure out which font file is chosen for a system generic font alias?Why are some apt-get-installed fonts being ignored by fc-list, xfontsel, etc?Reload settings in /etc/fonts/conf.dTaking 30 seconds longer to boot after upgrade from jessie to stretchHow to match multiple font names with a single <match> element?Adding a custom font to fontconfigRemoving fonts from fontconfig <match> resultsBroken fonts after upgrading Firefox ESR to latest Firefox