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

                              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