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:
len=${#array[@]}
Next, get the last command line argument from an array (i.e. $@ stored in an array):
_domain=${array[$len-1]}
Finally, extract and store all command line parameters before last parameter in $@:
args=${array[@]:0:$len-1}
Putting it all together:
#!/bin/bash array=( $@ ) len=${#array[@]} _domain=${array[$len-1]} _args=${array[@]:0:$len-1} echo "Domain: $_domain" echo "All Args before $_domain are: $_args"
Run it as follows:
./script -p -y --zzz cyberciti.biz
Sample outputs:
Domain: cyberciti.biz All Args before cyberciti.biz are: -p -y --zzz
Another sample run:
$ ./script -p -y --zzz --delete cyberciti.biz
Sample outputs:
Domain: cyberciti.biz All Args before cyberciti.biz are: -p -y --zzz --delete
You should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop














{ 0 comments… add one now }