How to get a bash script argument given its position from the end?











up vote
1
down vote

favorite












I've got a shell script and I want to use the last argument:



#!/bin/bash
echo My last param is #somehow put it here


Here is what I've tried:



echo $$#
echo ${$#}
echo ${(($#))}


Unfortunately it did not work.



In a broader sense, I would like to know how to access the Nth argument from the end. How do I achieve that?










share|improve this question




























    up vote
    1
    down vote

    favorite












    I've got a shell script and I want to use the last argument:



    #!/bin/bash
    echo My last param is #somehow put it here


    Here is what I've tried:



    echo $$#
    echo ${$#}
    echo ${(($#))}


    Unfortunately it did not work.



    In a broader sense, I would like to know how to access the Nth argument from the end. How do I achieve that?










    share|improve this question


























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I've got a shell script and I want to use the last argument:



      #!/bin/bash
      echo My last param is #somehow put it here


      Here is what I've tried:



      echo $$#
      echo ${$#}
      echo ${(($#))}


      Unfortunately it did not work.



      In a broader sense, I would like to know how to access the Nth argument from the end. How do I achieve that?










      share|improve this question















      I've got a shell script and I want to use the last argument:



      #!/bin/bash
      echo My last param is #somehow put it here


      Here is what I've tried:



      echo $$#
      echo ${$#}
      echo ${(($#))}


      Unfortunately it did not work.



      In a broader sense, I would like to know how to access the Nth argument from the end. How do I achieve that?







      shell-script shell






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 44 mins ago









      MatthewRock

      3,85321847




      3,85321847










      asked 1 hour ago









      YardenST

      1506




      1506






















          3 Answers
          3






          active

          oldest

          votes

















          up vote
          3
          down vote













          To get any argument, you can use slicing:



          #!/bin/bash

          # Get 3rd element from the end
          from_end1=3
          # Get last element
          from_end2=1

          # Get slice of array [end - from_end1 : end ] of length 1
          echo "${@: -$from_end1: 1}"
          echo "${@: -$from_end2: 1}"


          You can also use this to get Nth element:



          # Get 2nd element
          from_beginning=2

          echo "${@: $from_beginning: 1}"


          Remember to check for length; this might return your program's name or an empty string.






          share|improve this answer




























            up vote
            3
            down vote













            In bash (release 4.3+), you may assign the passed parameters to an array and access the last one by the index -1:



            #!/bin/bash

            params=( "$@" )
            printf 'The last parameter given to the script is %sn' "${params[-1]}"

            foo () {
            params=( "$@" )
            printf 'The last parameter given to the function is %sn' "${params[-1]}"
            }


            In general, negative indexes into arrays accesses the elements from the end of the array.






            share|improve this answer






























              up vote
              2
              down vote













              In addition (to Kusalananda's answer):



              #! /bin/bash 

              echo "(bash/ksh): ${@: -1}"
              echo "(bash 3.x+): ${!#}"
              echo "(bash 3.x+): $BASH_ARGV"
              echo "(bash 3.x+/ksh): ${@:$#}"
              echo "(bash 3.x+): ${BASH_ARGV[0]}"


              and if you worry about portability:



              #!/bin/bash

              penultimate=''
              ultimate=''

              for p in "$@" ; do
              penultimate="$ultimate"
              ultimate="$p"
              done

              echo "penultimate=$penultimate"
              echo "ultimate=$ultimate"





              share|improve this answer























              • to Kusalananda's answer.
                – Ljm Dullaart
                1 hour ago










              • Yes, you're right; I added it in the answer.
                – Ljm Dullaart
                1 hour ago










              • can you please explain about this notation? ${!#}
                – YardenST
                19 mins ago











              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',
              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%2f486657%2fhow-to-get-a-bash-script-argument-given-its-position-from-the-end%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              3
              down vote













              To get any argument, you can use slicing:



              #!/bin/bash

              # Get 3rd element from the end
              from_end1=3
              # Get last element
              from_end2=1

              # Get slice of array [end - from_end1 : end ] of length 1
              echo "${@: -$from_end1: 1}"
              echo "${@: -$from_end2: 1}"


              You can also use this to get Nth element:



              # Get 2nd element
              from_beginning=2

              echo "${@: $from_beginning: 1}"


              Remember to check for length; this might return your program's name or an empty string.






              share|improve this answer

























                up vote
                3
                down vote













                To get any argument, you can use slicing:



                #!/bin/bash

                # Get 3rd element from the end
                from_end1=3
                # Get last element
                from_end2=1

                # Get slice of array [end - from_end1 : end ] of length 1
                echo "${@: -$from_end1: 1}"
                echo "${@: -$from_end2: 1}"


                You can also use this to get Nth element:



                # Get 2nd element
                from_beginning=2

                echo "${@: $from_beginning: 1}"


                Remember to check for length; this might return your program's name or an empty string.






                share|improve this answer























                  up vote
                  3
                  down vote










                  up vote
                  3
                  down vote









                  To get any argument, you can use slicing:



                  #!/bin/bash

                  # Get 3rd element from the end
                  from_end1=3
                  # Get last element
                  from_end2=1

                  # Get slice of array [end - from_end1 : end ] of length 1
                  echo "${@: -$from_end1: 1}"
                  echo "${@: -$from_end2: 1}"


                  You can also use this to get Nth element:



                  # Get 2nd element
                  from_beginning=2

                  echo "${@: $from_beginning: 1}"


                  Remember to check for length; this might return your program's name or an empty string.






                  share|improve this answer












                  To get any argument, you can use slicing:



                  #!/bin/bash

                  # Get 3rd element from the end
                  from_end1=3
                  # Get last element
                  from_end2=1

                  # Get slice of array [end - from_end1 : end ] of length 1
                  echo "${@: -$from_end1: 1}"
                  echo "${@: -$from_end2: 1}"


                  You can also use this to get Nth element:



                  # Get 2nd element
                  from_beginning=2

                  echo "${@: $from_beginning: 1}"


                  Remember to check for length; this might return your program's name or an empty string.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 1 hour ago









                  MatthewRock

                  3,85321847




                  3,85321847
























                      up vote
                      3
                      down vote













                      In bash (release 4.3+), you may assign the passed parameters to an array and access the last one by the index -1:



                      #!/bin/bash

                      params=( "$@" )
                      printf 'The last parameter given to the script is %sn' "${params[-1]}"

                      foo () {
                      params=( "$@" )
                      printf 'The last parameter given to the function is %sn' "${params[-1]}"
                      }


                      In general, negative indexes into arrays accesses the elements from the end of the array.






                      share|improve this answer



























                        up vote
                        3
                        down vote













                        In bash (release 4.3+), you may assign the passed parameters to an array and access the last one by the index -1:



                        #!/bin/bash

                        params=( "$@" )
                        printf 'The last parameter given to the script is %sn' "${params[-1]}"

                        foo () {
                        params=( "$@" )
                        printf 'The last parameter given to the function is %sn' "${params[-1]}"
                        }


                        In general, negative indexes into arrays accesses the elements from the end of the array.






                        share|improve this answer

























                          up vote
                          3
                          down vote










                          up vote
                          3
                          down vote









                          In bash (release 4.3+), you may assign the passed parameters to an array and access the last one by the index -1:



                          #!/bin/bash

                          params=( "$@" )
                          printf 'The last parameter given to the script is %sn' "${params[-1]}"

                          foo () {
                          params=( "$@" )
                          printf 'The last parameter given to the function is %sn' "${params[-1]}"
                          }


                          In general, negative indexes into arrays accesses the elements from the end of the array.






                          share|improve this answer














                          In bash (release 4.3+), you may assign the passed parameters to an array and access the last one by the index -1:



                          #!/bin/bash

                          params=( "$@" )
                          printf 'The last parameter given to the script is %sn' "${params[-1]}"

                          foo () {
                          params=( "$@" )
                          printf 'The last parameter given to the function is %sn' "${params[-1]}"
                          }


                          In general, negative indexes into arrays accesses the elements from the end of the array.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited 36 mins ago

























                          answered 1 hour ago









                          Kusalananda

                          119k16223364




                          119k16223364






















                              up vote
                              2
                              down vote













                              In addition (to Kusalananda's answer):



                              #! /bin/bash 

                              echo "(bash/ksh): ${@: -1}"
                              echo "(bash 3.x+): ${!#}"
                              echo "(bash 3.x+): $BASH_ARGV"
                              echo "(bash 3.x+/ksh): ${@:$#}"
                              echo "(bash 3.x+): ${BASH_ARGV[0]}"


                              and if you worry about portability:



                              #!/bin/bash

                              penultimate=''
                              ultimate=''

                              for p in "$@" ; do
                              penultimate="$ultimate"
                              ultimate="$p"
                              done

                              echo "penultimate=$penultimate"
                              echo "ultimate=$ultimate"





                              share|improve this answer























                              • to Kusalananda's answer.
                                – Ljm Dullaart
                                1 hour ago










                              • Yes, you're right; I added it in the answer.
                                – Ljm Dullaart
                                1 hour ago










                              • can you please explain about this notation? ${!#}
                                – YardenST
                                19 mins ago















                              up vote
                              2
                              down vote













                              In addition (to Kusalananda's answer):



                              #! /bin/bash 

                              echo "(bash/ksh): ${@: -1}"
                              echo "(bash 3.x+): ${!#}"
                              echo "(bash 3.x+): $BASH_ARGV"
                              echo "(bash 3.x+/ksh): ${@:$#}"
                              echo "(bash 3.x+): ${BASH_ARGV[0]}"


                              and if you worry about portability:



                              #!/bin/bash

                              penultimate=''
                              ultimate=''

                              for p in "$@" ; do
                              penultimate="$ultimate"
                              ultimate="$p"
                              done

                              echo "penultimate=$penultimate"
                              echo "ultimate=$ultimate"





                              share|improve this answer























                              • to Kusalananda's answer.
                                – Ljm Dullaart
                                1 hour ago










                              • Yes, you're right; I added it in the answer.
                                – Ljm Dullaart
                                1 hour ago










                              • can you please explain about this notation? ${!#}
                                – YardenST
                                19 mins ago













                              up vote
                              2
                              down vote










                              up vote
                              2
                              down vote









                              In addition (to Kusalananda's answer):



                              #! /bin/bash 

                              echo "(bash/ksh): ${@: -1}"
                              echo "(bash 3.x+): ${!#}"
                              echo "(bash 3.x+): $BASH_ARGV"
                              echo "(bash 3.x+/ksh): ${@:$#}"
                              echo "(bash 3.x+): ${BASH_ARGV[0]}"


                              and if you worry about portability:



                              #!/bin/bash

                              penultimate=''
                              ultimate=''

                              for p in "$@" ; do
                              penultimate="$ultimate"
                              ultimate="$p"
                              done

                              echo "penultimate=$penultimate"
                              echo "ultimate=$ultimate"





                              share|improve this answer














                              In addition (to Kusalananda's answer):



                              #! /bin/bash 

                              echo "(bash/ksh): ${@: -1}"
                              echo "(bash 3.x+): ${!#}"
                              echo "(bash 3.x+): $BASH_ARGV"
                              echo "(bash 3.x+/ksh): ${@:$#}"
                              echo "(bash 3.x+): ${BASH_ARGV[0]}"


                              and if you worry about portability:



                              #!/bin/bash

                              penultimate=''
                              ultimate=''

                              for p in "$@" ; do
                              penultimate="$ultimate"
                              ultimate="$p"
                              done

                              echo "penultimate=$penultimate"
                              echo "ultimate=$ultimate"






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited 1 hour ago









                              Kusalananda

                              119k16223364




                              119k16223364










                              answered 1 hour ago









                              Ljm Dullaart

                              55017




                              55017












                              • to Kusalananda's answer.
                                – Ljm Dullaart
                                1 hour ago










                              • Yes, you're right; I added it in the answer.
                                – Ljm Dullaart
                                1 hour ago










                              • can you please explain about this notation? ${!#}
                                – YardenST
                                19 mins ago


















                              • to Kusalananda's answer.
                                – Ljm Dullaart
                                1 hour ago










                              • Yes, you're right; I added it in the answer.
                                – Ljm Dullaart
                                1 hour ago










                              • can you please explain about this notation? ${!#}
                                – YardenST
                                19 mins ago
















                              to Kusalananda's answer.
                              – Ljm Dullaart
                              1 hour ago




                              to Kusalananda's answer.
                              – Ljm Dullaart
                              1 hour ago












                              Yes, you're right; I added it in the answer.
                              – Ljm Dullaart
                              1 hour ago




                              Yes, you're right; I added it in the answer.
                              – Ljm Dullaart
                              1 hour ago












                              can you please explain about this notation? ${!#}
                              – YardenST
                              19 mins ago




                              can you please explain about this notation? ${!#}
                              – YardenST
                              19 mins ago


















                              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.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • 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%2f486657%2fhow-to-get-a-bash-script-argument-given-its-position-from-the-end%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