ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Yeah, you could use getopts.
But here's my favorite way to handle this:
Code:
#!/bin/sh
function error_exit() { echo "ERROR: $*" 1>&2; exit 1; }
ROOTPASS= USERPASS=
while test $# -gt 0; do
case "$1" in
-rp) shift; ROOTPASS="$1" ;;
-rp*) ROOTPASS="${1#-rp}" ;;
-nup) shift; USERPASS="$1" ;;
-nup*) USERPASS="${1#-nup}" ;;
*) error_exit "Unknown switch or argument \"$1\"" ;;
esac
shift
done
test -z "$ROOTPASS" && error_exit "No root password was given"
test -z "$USERPASS" && error_exit "No user password was given"
# Etcetera
As for the above function, it's not a bad solution for a simple script, although in the end it's really just a home-made, simplified getopts-style processor. Unlike getopts, you can personalize your option formats, but on the other hand it won't easily handle option combos (at least not without defining all the possible combinations), or catch missing argument errors without doing further tests.
I'd also like to add my two cents to the above:
Code:
while test $# -gt 0; do
# can be changed to...
while (( $# > 0 )); do
# or even just...
while (( $# )); do
Code:
others=( ${others[@]-} "$1" )
others=( ${others[@]-} "$@" )
# can be changed to...
others+=( "$1" )
others+=( "$@" )
Or is there any reason to use ${others[@]-} instead of ${others[@]}? All the first one does is set an empty element if the array was previously empty.
.........
PS to frieza: I posted a comment earlier to your previous thread with some suggestions for improving your script. Check it out.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.