Passing args from the bash script to the function in the script Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara 2019 Community Moderator Election Results Why I closed the “Why is Kali so hard” questionAre there naming conventions for variables in shell scripts?When is double-quoting necessary?How can we run a command stored in a variable?Passing a stream to a bash functionPassing script string to ssh from within a bash script function - variable evaluation problembash script - loop functionShell script - command always display usage before executingrsync using function argsBash script inheritance? Calling a function from another script?Passing options/args/parameters with spaces from the script to a function withinPassing a boolean flag to a function?Dynamically read bash function name from inside bash functionrunning bash script from cron job not working properly

How to find the right literary agent in the USA?

Raising a bilingual kid. When should we introduce the majority language?

Putting Ant-Man on house arrest

Why did C use the -> operator instead of reusing the . operator?

How would this chord from "Rocket Man" be analyzed?

Why does the Cisco show run command not show the full version, while the show version command does?

How long after the last departure shall the airport stay open for an emergency return?

Multiple fireplaces in an apartment building?

How do I check if a string is entirely made of the same substring?

What is ls Largest Number Formed by only moving two sticks in 508?

Align column where each cell has two decimals with siunitx

Where did Arya get these scars?

What is it called when you ride around on your front wheel?

How to translate "red flag" into Spanish?

What if Force was not Mass times Acceleration?

std::is_constructible on incomplete types

Is this homebrew racial feat, Stonehide, balanced?

Is Bran literally the world's memory?

What to do with someone that cheated their way through university and a PhD program?

What is "leading note" and what does it mean to "raise a note"?

Why did Israel vote against lifting the American embargo on Cuba?

Do I need to protect SFP ports and optics from dust/contaminants? If so, how?

Can I criticise the more senior developers around me for not writing clean code?

Identify story/novel: Tribe on colonized planet, not aware of this. "Taboo," altitude sickness, robot guardian (60s? Young Adult?)



Passing args from the bash script to the function in the script



Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
2019 Community Moderator Election Results
Why I closed the “Why is Kali so hard” questionAre there naming conventions for variables in shell scripts?When is double-quoting necessary?How can we run a command stored in a variable?Passing a stream to a bash functionPassing script string to ssh from within a bash script function - variable evaluation problembash script - loop functionShell script - command always display usage before executingrsync using function argsBash script inheritance? Calling a function from another script?Passing options/args/parameters with spaces from the script to a function withinPassing a boolean flag to a function?Dynamically read bash function name from inside bash functionrunning bash script from cron job not working properly



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








1















My script:



#! /bin/bash --

set -x

## docker-compose wrapper
compose_fn()
local ENV="$1"
local VERB="$2"
local SERVICE="$3"
local CMD="docker-compose -f $ENV.yml"
case "$VERB" in
(exec)
shift "$#" # remove args passed to this fn
# Execute a command in a running container.
if [ -n "$SERVICE" ]; then
$CMD "$VERB" "$SERVICE" "$@"
else
echo "## Err: You must specify service name..."
exit 1
fi
;;
esac


compose_fn "$1" "$2" "$3"


Is giving me a hard time with the following error:



$ ./tst.sh dev exec django sh
+ compose_fn dev exec django
+ local ENV=dev
+ local VERB=exec
+ local SERVICE=django
+ local 'CMD=docker-compose -f dev.yml'
+ case "$VERB" in
+ shift 3
+ '[' -n django ']'
+ docker-compose -f dev.yml exec django
Execute a command in a running container

Usage: exec [options] [-e KEY=VAL...] SERVICE COMMAND [ARGS...]

Options:
....


Where is my mistake? How can it be done better?



As far as I can tell I've passed 4 args [dev, exec, django, sh] to the script, then within the script removed 3 (shift 3), therefore sh should have been left in the $@ var.










share|improve this question






























    1















    My script:



    #! /bin/bash --

    set -x

    ## docker-compose wrapper
    compose_fn()
    local ENV="$1"
    local VERB="$2"
    local SERVICE="$3"
    local CMD="docker-compose -f $ENV.yml"
    case "$VERB" in
    (exec)
    shift "$#" # remove args passed to this fn
    # Execute a command in a running container.
    if [ -n "$SERVICE" ]; then
    $CMD "$VERB" "$SERVICE" "$@"
    else
    echo "## Err: You must specify service name..."
    exit 1
    fi
    ;;
    esac


    compose_fn "$1" "$2" "$3"


    Is giving me a hard time with the following error:



    $ ./tst.sh dev exec django sh
    + compose_fn dev exec django
    + local ENV=dev
    + local VERB=exec
    + local SERVICE=django
    + local 'CMD=docker-compose -f dev.yml'
    + case "$VERB" in
    + shift 3
    + '[' -n django ']'
    + docker-compose -f dev.yml exec django
    Execute a command in a running container

    Usage: exec [options] [-e KEY=VAL...] SERVICE COMMAND [ARGS...]

    Options:
    ....


    Where is my mistake? How can it be done better?



    As far as I can tell I've passed 4 args [dev, exec, django, sh] to the script, then within the script removed 3 (shift 3), therefore sh should have been left in the $@ var.










    share|improve this question


























      1












      1








      1








      My script:



      #! /bin/bash --

      set -x

      ## docker-compose wrapper
      compose_fn()
      local ENV="$1"
      local VERB="$2"
      local SERVICE="$3"
      local CMD="docker-compose -f $ENV.yml"
      case "$VERB" in
      (exec)
      shift "$#" # remove args passed to this fn
      # Execute a command in a running container.
      if [ -n "$SERVICE" ]; then
      $CMD "$VERB" "$SERVICE" "$@"
      else
      echo "## Err: You must specify service name..."
      exit 1
      fi
      ;;
      esac


      compose_fn "$1" "$2" "$3"


      Is giving me a hard time with the following error:



      $ ./tst.sh dev exec django sh
      + compose_fn dev exec django
      + local ENV=dev
      + local VERB=exec
      + local SERVICE=django
      + local 'CMD=docker-compose -f dev.yml'
      + case "$VERB" in
      + shift 3
      + '[' -n django ']'
      + docker-compose -f dev.yml exec django
      Execute a command in a running container

      Usage: exec [options] [-e KEY=VAL...] SERVICE COMMAND [ARGS...]

      Options:
      ....


      Where is my mistake? How can it be done better?



      As far as I can tell I've passed 4 args [dev, exec, django, sh] to the script, then within the script removed 3 (shift 3), therefore sh should have been left in the $@ var.










      share|improve this question
















      My script:



      #! /bin/bash --

      set -x

      ## docker-compose wrapper
      compose_fn()
      local ENV="$1"
      local VERB="$2"
      local SERVICE="$3"
      local CMD="docker-compose -f $ENV.yml"
      case "$VERB" in
      (exec)
      shift "$#" # remove args passed to this fn
      # Execute a command in a running container.
      if [ -n "$SERVICE" ]; then
      $CMD "$VERB" "$SERVICE" "$@"
      else
      echo "## Err: You must specify service name..."
      exit 1
      fi
      ;;
      esac


      compose_fn "$1" "$2" "$3"


      Is giving me a hard time with the following error:



      $ ./tst.sh dev exec django sh
      + compose_fn dev exec django
      + local ENV=dev
      + local VERB=exec
      + local SERVICE=django
      + local 'CMD=docker-compose -f dev.yml'
      + case "$VERB" in
      + shift 3
      + '[' -n django ']'
      + docker-compose -f dev.yml exec django
      Execute a command in a running container

      Usage: exec [options] [-e KEY=VAL...] SERVICE COMMAND [ARGS...]

      Options:
      ....


      Where is my mistake? How can it be done better?



      As far as I can tell I've passed 4 args [dev, exec, django, sh] to the script, then within the script removed 3 (shift 3), therefore sh should have been left in the $@ var.







      bash shell-script shell






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 43 mins ago







      NarūnasK

















      asked 1 hour ago









      NarūnasKNarūnasK

      9171722




      9171722




















          1 Answer
          1






          active

          oldest

          votes


















          4














          With shift $# you empty $@ completely. The $@ in the function is separate from the $@ in the main script. Why don't you just pass all arguments to the function and then shift off the first three?



          #! /bin/bash --

          set -x

          ## docker-compose wrapper
          compose_fn()
          local env="$1"
          local verb="$2"
          local service="$3"

          local cmd=( docker-compose -f "$env.yml" )

          shift 3 # we've now used up three arguments

          case $verb in
          exec)
          # Execute a command in a running container.
          if [ -n "$service" ]; then
          "$cmd[@]" "$verb" "$service" "$@"
          else
          echo '## Err: You must specify service name...' >&2
          exit 1
          fi
          ;;
          *)
          printf 'Unknown verb: %sn' "$verb" >&2
          exit 1
          esac


          compose_fn "$@"


          I've also used lower-case variable names so that no system or special shell variables are used by accident (ENV is one that some shell uses under some circumstances, for example), and I've removed all unneeded quotes and curly braces.



          I've also put the command into an array, so that we can quote the YAML filename properly.



          You could also just move the setting of the three variables outside of the function, depending on what the rest of the script looks like and if this makes any sense at all. The three variables would then be global in the script.



          #! /bin/bash --

          set -x

          ## docker-compose wrapper
          compose_fn()
          local cmd=( docker-compose -f "$env.yml" )

          case $verb in
          exec)
          # Execute a command in a running container.
          if [ -n "$service" ]; then
          "$cmd[@]" "$verb" "$service" "$@"
          else
          echo '## Err: You must specify service name...' >&2
          exit 1
          fi
          ;;
          *)
          printf 'Unknown verb: %sn' "$verb" >&2
          exit 1
          esac


          env="$1"
          verb="$2"
          service="$3"

          shift 3

          compose_fn "$@"


          You may also bypass the [ -n "$service" ] test with



          service=$3:?'## Err: You must specify service name...'


          The parameter expansion $parameter:?word will exit the shell with the message defined by word if parameter is unset or empty. The bash shell would format this as



          script.sh: line 9: 3: ## Err: You must specify service name...


          Related:



          • When is double-quoting necessary?

          • How can we run a command stored in a variable?

          • Are there naming conventions for variables in shell scripts?





          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%2f515342%2fpassing-args-from-the-bash-script-to-the-function-in-the-script%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            4














            With shift $# you empty $@ completely. The $@ in the function is separate from the $@ in the main script. Why don't you just pass all arguments to the function and then shift off the first three?



            #! /bin/bash --

            set -x

            ## docker-compose wrapper
            compose_fn()
            local env="$1"
            local verb="$2"
            local service="$3"

            local cmd=( docker-compose -f "$env.yml" )

            shift 3 # we've now used up three arguments

            case $verb in
            exec)
            # Execute a command in a running container.
            if [ -n "$service" ]; then
            "$cmd[@]" "$verb" "$service" "$@"
            else
            echo '## Err: You must specify service name...' >&2
            exit 1
            fi
            ;;
            *)
            printf 'Unknown verb: %sn' "$verb" >&2
            exit 1
            esac


            compose_fn "$@"


            I've also used lower-case variable names so that no system or special shell variables are used by accident (ENV is one that some shell uses under some circumstances, for example), and I've removed all unneeded quotes and curly braces.



            I've also put the command into an array, so that we can quote the YAML filename properly.



            You could also just move the setting of the three variables outside of the function, depending on what the rest of the script looks like and if this makes any sense at all. The three variables would then be global in the script.



            #! /bin/bash --

            set -x

            ## docker-compose wrapper
            compose_fn()
            local cmd=( docker-compose -f "$env.yml" )

            case $verb in
            exec)
            # Execute a command in a running container.
            if [ -n "$service" ]; then
            "$cmd[@]" "$verb" "$service" "$@"
            else
            echo '## Err: You must specify service name...' >&2
            exit 1
            fi
            ;;
            *)
            printf 'Unknown verb: %sn' "$verb" >&2
            exit 1
            esac


            env="$1"
            verb="$2"
            service="$3"

            shift 3

            compose_fn "$@"


            You may also bypass the [ -n "$service" ] test with



            service=$3:?'## Err: You must specify service name...'


            The parameter expansion $parameter:?word will exit the shell with the message defined by word if parameter is unset or empty. The bash shell would format this as



            script.sh: line 9: 3: ## Err: You must specify service name...


            Related:



            • When is double-quoting necessary?

            • How can we run a command stored in a variable?

            • Are there naming conventions for variables in shell scripts?





            share|improve this answer





























              4














              With shift $# you empty $@ completely. The $@ in the function is separate from the $@ in the main script. Why don't you just pass all arguments to the function and then shift off the first three?



              #! /bin/bash --

              set -x

              ## docker-compose wrapper
              compose_fn()
              local env="$1"
              local verb="$2"
              local service="$3"

              local cmd=( docker-compose -f "$env.yml" )

              shift 3 # we've now used up three arguments

              case $verb in
              exec)
              # Execute a command in a running container.
              if [ -n "$service" ]; then
              "$cmd[@]" "$verb" "$service" "$@"
              else
              echo '## Err: You must specify service name...' >&2
              exit 1
              fi
              ;;
              *)
              printf 'Unknown verb: %sn' "$verb" >&2
              exit 1
              esac


              compose_fn "$@"


              I've also used lower-case variable names so that no system or special shell variables are used by accident (ENV is one that some shell uses under some circumstances, for example), and I've removed all unneeded quotes and curly braces.



              I've also put the command into an array, so that we can quote the YAML filename properly.



              You could also just move the setting of the three variables outside of the function, depending on what the rest of the script looks like and if this makes any sense at all. The three variables would then be global in the script.



              #! /bin/bash --

              set -x

              ## docker-compose wrapper
              compose_fn()
              local cmd=( docker-compose -f "$env.yml" )

              case $verb in
              exec)
              # Execute a command in a running container.
              if [ -n "$service" ]; then
              "$cmd[@]" "$verb" "$service" "$@"
              else
              echo '## Err: You must specify service name...' >&2
              exit 1
              fi
              ;;
              *)
              printf 'Unknown verb: %sn' "$verb" >&2
              exit 1
              esac


              env="$1"
              verb="$2"
              service="$3"

              shift 3

              compose_fn "$@"


              You may also bypass the [ -n "$service" ] test with



              service=$3:?'## Err: You must specify service name...'


              The parameter expansion $parameter:?word will exit the shell with the message defined by word if parameter is unset or empty. The bash shell would format this as



              script.sh: line 9: 3: ## Err: You must specify service name...


              Related:



              • When is double-quoting necessary?

              • How can we run a command stored in a variable?

              • Are there naming conventions for variables in shell scripts?





              share|improve this answer



























                4












                4








                4







                With shift $# you empty $@ completely. The $@ in the function is separate from the $@ in the main script. Why don't you just pass all arguments to the function and then shift off the first three?



                #! /bin/bash --

                set -x

                ## docker-compose wrapper
                compose_fn()
                local env="$1"
                local verb="$2"
                local service="$3"

                local cmd=( docker-compose -f "$env.yml" )

                shift 3 # we've now used up three arguments

                case $verb in
                exec)
                # Execute a command in a running container.
                if [ -n "$service" ]; then
                "$cmd[@]" "$verb" "$service" "$@"
                else
                echo '## Err: You must specify service name...' >&2
                exit 1
                fi
                ;;
                *)
                printf 'Unknown verb: %sn' "$verb" >&2
                exit 1
                esac


                compose_fn "$@"


                I've also used lower-case variable names so that no system or special shell variables are used by accident (ENV is one that some shell uses under some circumstances, for example), and I've removed all unneeded quotes and curly braces.



                I've also put the command into an array, so that we can quote the YAML filename properly.



                You could also just move the setting of the three variables outside of the function, depending on what the rest of the script looks like and if this makes any sense at all. The three variables would then be global in the script.



                #! /bin/bash --

                set -x

                ## docker-compose wrapper
                compose_fn()
                local cmd=( docker-compose -f "$env.yml" )

                case $verb in
                exec)
                # Execute a command in a running container.
                if [ -n "$service" ]; then
                "$cmd[@]" "$verb" "$service" "$@"
                else
                echo '## Err: You must specify service name...' >&2
                exit 1
                fi
                ;;
                *)
                printf 'Unknown verb: %sn' "$verb" >&2
                exit 1
                esac


                env="$1"
                verb="$2"
                service="$3"

                shift 3

                compose_fn "$@"


                You may also bypass the [ -n "$service" ] test with



                service=$3:?'## Err: You must specify service name...'


                The parameter expansion $parameter:?word will exit the shell with the message defined by word if parameter is unset or empty. The bash shell would format this as



                script.sh: line 9: 3: ## Err: You must specify service name...


                Related:



                • When is double-quoting necessary?

                • How can we run a command stored in a variable?

                • Are there naming conventions for variables in shell scripts?





                share|improve this answer















                With shift $# you empty $@ completely. The $@ in the function is separate from the $@ in the main script. Why don't you just pass all arguments to the function and then shift off the first three?



                #! /bin/bash --

                set -x

                ## docker-compose wrapper
                compose_fn()
                local env="$1"
                local verb="$2"
                local service="$3"

                local cmd=( docker-compose -f "$env.yml" )

                shift 3 # we've now used up three arguments

                case $verb in
                exec)
                # Execute a command in a running container.
                if [ -n "$service" ]; then
                "$cmd[@]" "$verb" "$service" "$@"
                else
                echo '## Err: You must specify service name...' >&2
                exit 1
                fi
                ;;
                *)
                printf 'Unknown verb: %sn' "$verb" >&2
                exit 1
                esac


                compose_fn "$@"


                I've also used lower-case variable names so that no system or special shell variables are used by accident (ENV is one that some shell uses under some circumstances, for example), and I've removed all unneeded quotes and curly braces.



                I've also put the command into an array, so that we can quote the YAML filename properly.



                You could also just move the setting of the three variables outside of the function, depending on what the rest of the script looks like and if this makes any sense at all. The three variables would then be global in the script.



                #! /bin/bash --

                set -x

                ## docker-compose wrapper
                compose_fn()
                local cmd=( docker-compose -f "$env.yml" )

                case $verb in
                exec)
                # Execute a command in a running container.
                if [ -n "$service" ]; then
                "$cmd[@]" "$verb" "$service" "$@"
                else
                echo '## Err: You must specify service name...' >&2
                exit 1
                fi
                ;;
                *)
                printf 'Unknown verb: %sn' "$verb" >&2
                exit 1
                esac


                env="$1"
                verb="$2"
                service="$3"

                shift 3

                compose_fn "$@"


                You may also bypass the [ -n "$service" ] test with



                service=$3:?'## Err: You must specify service name...'


                The parameter expansion $parameter:?word will exit the shell with the message defined by word if parameter is unset or empty. The bash shell would format this as



                script.sh: line 9: 3: ## Err: You must specify service name...


                Related:



                • When is double-quoting necessary?

                • How can we run a command stored in a variable?

                • Are there naming conventions for variables in shell scripts?






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 15 mins ago

























                answered 32 mins ago









                KusalanandaKusalananda

                143k18267445




                143k18267445



























                    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%2f515342%2fpassing-args-from-the-bash-script-to-the-function-in-the-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







                    Popular posts from this blog

                    Are there any AGPL-style licences that require source code modifications to be public? Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Force derivative works to be publicAre there any GPL like licenses for Apple App Store?Do you violate the GPL if you provide source code that cannot be compiled?GPL - is it distribution to use libraries in an appliance loaned to customers?Distributing App for free which uses GPL'ed codeModifications of server software under GPL, with web/CLI interfaceDoes using an AGPLv3-licensed library prevent me from dual-licensing my own source code?Can I publish only select code under GPLv3 from a private project?Is there published precedent regarding the scope of covered work that uses AGPL software?If MIT licensed code links to GPL licensed code what should be the license of the resulting binary program?If I use a public API endpoint that has its source code licensed under AGPL in my app, do I need to disclose my source?

                    2013 GY136 Descoberta | Órbita | Referências Menu de navegação«List Of Centaurs and Scattered-Disk Objects»«List of Known Trans-Neptunian Objects»

                    Button changing it's text & action. Good or terrible? The 2019 Stack Overflow Developer Survey Results Are Inchanging text on user mouseoverShould certain functions be “hard to find” for powerusers to discover?Custom liking function - do I need user login?Using different checkbox style for different checkbox behaviorBest Practices: Save and Exit in Software UIInteraction with remote validated formMore efficient UI to progress the user through a complicated process?Designing a popup notice for a gameShould bulk-editing functions be hidden until a table row is selected, or is there a better solution?Is it bad practice to disable (replace) the context menu?