Bash Get All Command Line Arguments Before Last Parameter In $@

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 $@ 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. $@ stored in an array):


Finally, extract and store all command line parameters before last parameter in $@:


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

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum