Bash Get All Command Line Arguments Before Last Parameter In [email protected]

Posted on in Categories last updated June 19, 2012

I‘m writing a wrapper bash shell script that will get the last argument (a domain name) from the command line into a shell variable called $_domain. I need to find all other parameters before last parameter in [email protected] and stored in a shell variable called $allargs. So that I can pass them as follows:

/path/to/real/binary “$allargs” “$_domain”

How do I do this using bash shell under Unix like operating systems?

You can store all command line arguments or parameter in a bash array as follows:

array=( $@ )

First, you need to find out length of an array:


Next, get the last command line argument from an array (i.e. [email protected] stored in an array):


Finally, extract and store all command line parameters before last parameter in [email protected]:


Putting it all together:

array=( $@ )
echo "Domain: $_domain"
echo "All Args before $_domain are: $_args"

Run it as follows:
./script -p -y --zzz
Sample outputs:

All Args before are: -p -y --zzz

Another sample run:
$ ./script -p -y --zzz --delete
Sample outputs:

All Args before are: -p -y --zzz --delete

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Share this on (or read 0 comments/add one below):

Leave a Comment