Function Recursion in shell 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” questionDo shells support recursion?What's meaning the of a pair of parentheses after a string literal?Why isn't this `expr … | bc -l` command working?Differences between reserved word and command `time` on shell builtin, function, pipeline and command list?bash: Why are () causing error in script but not on the command line?How to pass parameters to function in a bash script?Why does local fn=$(…) mask the $? status codeTrying to exit script with a status code but getting “unexpected end of file”find: paths must precede expression: in bash shell scriptPassing variable to “authorization: bearer” header with Curl and Bash

Can I cast Passwall to drop an enemy into a 20-foot pit?

The logistics of corpse disposal

How come Sam didn't become Lord of Horn Hill?

What's the purpose of writing one's academic biography in the third person?

Why is "Consequences inflicted." not a sentence?

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

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

Why is my conclusion inconsistent with the van't Hoff equation?

Is the Standard Deduction better than Itemized when both are the same amount?

Bete Noir -- no dairy

Identify plant with long narrow paired leaves and reddish stems

What is Arya's weapon design?

At the end of Thor: Ragnarok why don't the Asgardians turn and head for the Bifrost as per their original plan?

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

How do pianists reach extremely loud dynamics?

How do I stop a creek from eroding my steep embankment?

List of Python versions

Why was the term "discrete" used in discrete logarithm?

Why didn't this character "real die" when they blew their stack out in Altered Carbon?

How widely used is the term Treppenwitz? Is it something that most Germans know?

How to deal with a team lead who never gives me credit?

Seeking colloquialism for “just because”

Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

51k Euros annually for a family of 4 in Berlin: Is it enough?



Function Recursion in shell



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” questionDo shells support recursion?What's meaning the of a pair of parentheses after a string literal?Why isn't this `expr … | bc -l` command working?Differences between reserved word and command `time` on shell builtin, function, pipeline and command list?bash: Why are () causing error in script but not on the command line?How to pass parameters to function in a bash script?Why does local fn=$(…) mask the $? status codeTrying to exit script with a status code but getting “unexpected end of file”find: paths must precede expression: in bash shell scriptPassing variable to “authorization: bearer” header with Curl and Bash



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








1















I'd like to know why this recursive function in shell works properly:



exp ( )

local result
#local op1="$1"
#echo $2
if [[ $2 -eq 0 ]]; then
echo 1
return
fi
tmp=$(( $2 - 1 ))
local result1=$(exp $1 $tmp )
result=$(( $result1 * $1 ))
echo $result

exp 3 4


But when touching $2 in any way, for example like this:



exp ( )

local result
echo $2
if [[ $2 -eq 0 ]]; then
echo 1
return
fi
tmp=$(( $2 - 1 ))
local result1=$(exp $1 $tmp )
result=$(( $result1 * $1 ))
echo $result

exp 3 4


It fails with:



4
foo.sh: line 15: 0
1 * 3 : syntax error in expression (error token is "1 * 3 ")
foo.sh: line 15: 2
3 * 3 : syntax error in expression (error token is "3 * 3 ")
9









share|improve this question






























    1















    I'd like to know why this recursive function in shell works properly:



    exp ( )

    local result
    #local op1="$1"
    #echo $2
    if [[ $2 -eq 0 ]]; then
    echo 1
    return
    fi
    tmp=$(( $2 - 1 ))
    local result1=$(exp $1 $tmp )
    result=$(( $result1 * $1 ))
    echo $result

    exp 3 4


    But when touching $2 in any way, for example like this:



    exp ( )

    local result
    echo $2
    if [[ $2 -eq 0 ]]; then
    echo 1
    return
    fi
    tmp=$(( $2 - 1 ))
    local result1=$(exp $1 $tmp )
    result=$(( $result1 * $1 ))
    echo $result

    exp 3 4


    It fails with:



    4
    foo.sh: line 15: 0
    1 * 3 : syntax error in expression (error token is "1 * 3 ")
    foo.sh: line 15: 2
    3 * 3 : syntax error in expression (error token is "3 * 3 ")
    9









    share|improve this question


























      1












      1








      1








      I'd like to know why this recursive function in shell works properly:



      exp ( )

      local result
      #local op1="$1"
      #echo $2
      if [[ $2 -eq 0 ]]; then
      echo 1
      return
      fi
      tmp=$(( $2 - 1 ))
      local result1=$(exp $1 $tmp )
      result=$(( $result1 * $1 ))
      echo $result

      exp 3 4


      But when touching $2 in any way, for example like this:



      exp ( )

      local result
      echo $2
      if [[ $2 -eq 0 ]]; then
      echo 1
      return
      fi
      tmp=$(( $2 - 1 ))
      local result1=$(exp $1 $tmp )
      result=$(( $result1 * $1 ))
      echo $result

      exp 3 4


      It fails with:



      4
      foo.sh: line 15: 0
      1 * 3 : syntax error in expression (error token is "1 * 3 ")
      foo.sh: line 15: 2
      3 * 3 : syntax error in expression (error token is "3 * 3 ")
      9









      share|improve this question
















      I'd like to know why this recursive function in shell works properly:



      exp ( )

      local result
      #local op1="$1"
      #echo $2
      if [[ $2 -eq 0 ]]; then
      echo 1
      return
      fi
      tmp=$(( $2 - 1 ))
      local result1=$(exp $1 $tmp )
      result=$(( $result1 * $1 ))
      echo $result

      exp 3 4


      But when touching $2 in any way, for example like this:



      exp ( )

      local result
      echo $2
      if [[ $2 -eq 0 ]]; then
      echo 1
      return
      fi
      tmp=$(( $2 - 1 ))
      local result1=$(exp $1 $tmp )
      result=$(( $result1 * $1 ))
      echo $result

      exp 3 4


      It fails with:



      4
      foo.sh: line 15: 0
      1 * 3 : syntax error in expression (error token is "1 * 3 ")
      foo.sh: line 15: 2
      3 * 3 : syntax error in expression (error token is "3 * 3 ")
      9






      bash






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 10 hours ago









      terdon

      134k33270450




      134k33270450










      asked 10 hours ago









      Ahmed EdrisAhmed Edris

      142




      142




















          2 Answers
          2






          active

          oldest

          votes


















          1














          Invoke exp 3 0, save it as result1 and ask yourself if $(( $result1 * $1 )) makes sense now.



          The function expects itself to print one number. You make it print (echo) two numbers. At some point result1 contains two numbers and then result=$(( $result1 * $1 )) is syntactically wrong.






          share|improve this answer






























            1














            The problem isn't that you touch $2, it's that you echo stuff. Your function is, as you say, recursive. This means that it will process its own output. As soon as you have it printing out anything other than a single return number (which is what you expect), it will break.



            Specifically, your function will do this:



             tmp=$(( $2 - 1 ))
            local result1=$(exp $1 $tmp )
            result=$(( $result1 * $1 ))
            echo $result


            This works fine when the output of exp $1 $tmp, which is saved as result1 is just a single number. However, when you echo something else, the output of exp is no longer a single number so the simple math operations you do will break.






            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%2f512808%2ffunction-recursion-in-shell%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









              1














              Invoke exp 3 0, save it as result1 and ask yourself if $(( $result1 * $1 )) makes sense now.



              The function expects itself to print one number. You make it print (echo) two numbers. At some point result1 contains two numbers and then result=$(( $result1 * $1 )) is syntactically wrong.






              share|improve this answer



























                1














                Invoke exp 3 0, save it as result1 and ask yourself if $(( $result1 * $1 )) makes sense now.



                The function expects itself to print one number. You make it print (echo) two numbers. At some point result1 contains two numbers and then result=$(( $result1 * $1 )) is syntactically wrong.






                share|improve this answer

























                  1












                  1








                  1







                  Invoke exp 3 0, save it as result1 and ask yourself if $(( $result1 * $1 )) makes sense now.



                  The function expects itself to print one number. You make it print (echo) two numbers. At some point result1 contains two numbers and then result=$(( $result1 * $1 )) is syntactically wrong.






                  share|improve this answer













                  Invoke exp 3 0, save it as result1 and ask yourself if $(( $result1 * $1 )) makes sense now.



                  The function expects itself to print one number. You make it print (echo) two numbers. At some point result1 contains two numbers and then result=$(( $result1 * $1 )) is syntactically wrong.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 10 hours ago









                  Kamil MaciorowskiKamil Maciorowski

                  1,75711030




                  1,75711030























                      1














                      The problem isn't that you touch $2, it's that you echo stuff. Your function is, as you say, recursive. This means that it will process its own output. As soon as you have it printing out anything other than a single return number (which is what you expect), it will break.



                      Specifically, your function will do this:



                       tmp=$(( $2 - 1 ))
                      local result1=$(exp $1 $tmp )
                      result=$(( $result1 * $1 ))
                      echo $result


                      This works fine when the output of exp $1 $tmp, which is saved as result1 is just a single number. However, when you echo something else, the output of exp is no longer a single number so the simple math operations you do will break.






                      share|improve this answer



























                        1














                        The problem isn't that you touch $2, it's that you echo stuff. Your function is, as you say, recursive. This means that it will process its own output. As soon as you have it printing out anything other than a single return number (which is what you expect), it will break.



                        Specifically, your function will do this:



                         tmp=$(( $2 - 1 ))
                        local result1=$(exp $1 $tmp )
                        result=$(( $result1 * $1 ))
                        echo $result


                        This works fine when the output of exp $1 $tmp, which is saved as result1 is just a single number. However, when you echo something else, the output of exp is no longer a single number so the simple math operations you do will break.






                        share|improve this answer

























                          1












                          1








                          1







                          The problem isn't that you touch $2, it's that you echo stuff. Your function is, as you say, recursive. This means that it will process its own output. As soon as you have it printing out anything other than a single return number (which is what you expect), it will break.



                          Specifically, your function will do this:



                           tmp=$(( $2 - 1 ))
                          local result1=$(exp $1 $tmp )
                          result=$(( $result1 * $1 ))
                          echo $result


                          This works fine when the output of exp $1 $tmp, which is saved as result1 is just a single number. However, when you echo something else, the output of exp is no longer a single number so the simple math operations you do will break.






                          share|improve this answer













                          The problem isn't that you touch $2, it's that you echo stuff. Your function is, as you say, recursive. This means that it will process its own output. As soon as you have it printing out anything other than a single return number (which is what you expect), it will break.



                          Specifically, your function will do this:



                           tmp=$(( $2 - 1 ))
                          local result1=$(exp $1 $tmp )
                          result=$(( $result1 * $1 ))
                          echo $result


                          This works fine when the output of exp $1 $tmp, which is saved as result1 is just a single number. However, when you echo something else, the output of exp is no longer a single number so the simple math operations you do will break.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 10 hours ago









                          terdonterdon

                          134k33270450




                          134k33270450



























                              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%2f512808%2ffunction-recursion-in-shell%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







                              -bash

                              Popular posts from this blog

                              Creating 100m^2 grid automatically using QGIS?Creating grid constrained within polygon in QGIS?Createing polygon layer from point data using QGIS?Creating vector grid using QGIS?Creating grid polygons from coordinates using R or PythonCreating grid from spatio temporal point data?Creating fields in attributes table using other layers using QGISCreate .shp vector grid in QGISQGIS Creating 4km point grid within polygonsCreate a vector grid over a raster layerVector Grid Creates just one grid

                              Nikolai Prilezhaev Bibliography References External links Navigation menuEarly Russian Organic Chemists and Their Legacy092774english translationRussian Biography

                              How to link a C library to an Assembly library on Mac with clangHow do you set, clear, and toggle a single bit?Find (and kill) process locking port 3000 on MacWho is listening on a given TCP port on Mac OS X?How to start PostgreSQL server on Mac OS X?Compile assembler in nasm on mac osHow do I install pip on macOS or OS X?AFNetworking 2.0 “_NSURLSessionTransferSizeUnknown” linking error on Mac OS X 10.8C++ code for testing the Collatz conjecture faster than hand-written assembly - why?How to link a NASM code and GCC in Mac OS X?How to run x86 .asm on macOS Sierra