Bash - Best way to have helpFunction & default parameter values - bash

After a lot of read, SO or others, I'm really wondering about the best / cleanest way to have a bash script with parameters, optionals with default values.
Here is my script for now:
#!/bin/bash
helpFunction()
{
echo ""
echo "Usage: $0 --reload --mode=[single|cluster]"
echo -e "\t--reload Reload the database : fixtures & schema"
echo -e "\t--mode Mode of build : single or cluster"
exit 1
}
while [[ "$#" -gt 0 ]]; do
case $1 in
-h|--help) helpFunction; shift ;;
-r|--reload) reload=true; shift ;;
-m|--mode) mode="single"; shift ;;
# ... (same format for other required arguments)
*) echo "Unknown parameter passed: $1" ;;
esac
shift
done
./bin/sh/tools/build.sh -e local -m $mode -p local
For now, the $mode variable seems to not be set if I don't set it, how can I have a default value for this variable ? (default is single)
What I want is the user to call the script like (reload is true, mode is cluster):
bin/script.sh -r --mode=cluster
Or by default (reload is false, mode is single):
bin/script.sh
Is this the good way to wait for parameters ? I read other ways, but no real explanations.
Thanks.

There is no universal best/cleanest method; it eventually comes down to what works best for you; some ideas:
set mode to a default value before the while/case loop
after the while/case loop test mode and if unset/undefined then set to a
default value (should probably play it safe and unset mode before the while/case loop though in this case you might as well see idea #1)
pass to build.sh wrapped in double quotes (ie, build.sh -e local -m "$mode" -p local) and have build.sh test for the -m argument being unset/undefined and set to a default value
a variation on #2 and #3 is to use parameter substitution when
passing mode to build.sh, eg: build.sh -e local -m "${mode:-default_value}" -p local
if your script sources a config/ini file you could assign mode a
default value in said config/ini file and then make sure said config/ini file is sourced before the while/case loop

If you set the mode beforehand, that will be its default. If you want parameter with assignment, you need to grab $2 and shift twice.
mode="single"
while [[ "$#" -gt 0 ]]; do
case $1 in
-h|--help) helpFunction; shift ;;
-r|--reload) reload=true; shift ;;
-m|--mode) mode="$2"; shift; shift ;;
# ... (same format for other required arguments)
*) echo "Unknown parameter passed: $1" ;;
esac
shift
done
I think it's also good to restore the positional arguments. Since you may want to use them, but that depends on your script.
mode="single"
reload="false"
POSITIONAL=()
while [[ "$#" -gt 0 ]]; do
case $1 in
-h | --help)
helpFunction
shift
;;
-r | --reload)
reload=true
shift
;;
-m | --mode)
mode="$2"
shift
shift
;;
*)
POSITIONAL+=("$1")
shift
;;
esac
done
set -- "${POSITIONAL[#]}"
COMMAND="$1"
Then you could invoke a function that is called like the $COMMAND and pass the rest of the params with $#, and shift again and set the subcommand to $1. You can do this infinitely to get a chain of (sub)commands.
You can still check if a valid command was provided before you try to call the $COMMAND.
COMMAND_LIST="add issue revoke"
case $COMMAND_LIST in
*"$COMMAND"*)
"$COMMAND" "$#"
;;
*)
helpFunction
echo "ERROR: Unknown command: $COMMAND"
exit 1
;;
esac
But that is of course only if your script supports commands/subcommands. Otherwise, it makes sense to error right away like you did, if there is an unknown parameter.

Related

Bash optarg fails to spot missing arguments

I am inexperienced with bash shell scripting, and have run into a problem with bash optarg
Here's a small script to reproduce the problem:
#!/bin/sh
while getopts ":a:b:" opt; do
case ${opt} in
a ) echo "a=$OPTARG"
;;
b ) echo "b=$OPTARG"
;;
\? ) echo "Invalid option: $OPTARG" 1>&2
;;
: ) echo "Invalid option: $OPTARG requires an argument" 1>&2
esac
done
When I try this:
./args.sh -a av -b bv
I get the expected result:
a=av
b=bv
But when I omit the argument for -a:
/args.sh -a -b bv
I get this unfortunate result:
a=-b
When I would expect an error to show that the value of -a is missing.
It seems to have taken the -b argument as the value for -a.
Have I done something wrong & how can I achieve the expected behaviour?
The only positive advice is how do you treat But when I omit the argument for '-a', you cannot just skip to the next subsequent option. By convention getopts a: means you are expecting to an provide an arg value for the flag defined.
So even for the omitting case, you need to define an empty string which means the value for the arg is not defined i.e.
-a '' -b bv
Or if you don't expect the -a to get any arg values, better change the option string to not receive any as :ab:.
Any other ways of working around by checking if the OPTARG for -a is does not contain - or other hacks are not advised as it does not comply with the getopts() work flow.
getopts doesn't support such detection. So there's no way to do that with getopts.
You can probably write a loop around the arguments instead. something like:
#!/bin/sh
check_option()
{
case $1 in
-*)
return 1
;;
esac
return 0
}
for opt in $#; do
case ${opt} in
-a) shift
if check_option $1; then
echo "arg for -a: $1"
shift
else
echo "Invalid option -a"
fi
;;
-b) shift
if check_option $1; then
echo "arg for -b: $1"
shift
else
echo "Invalid option -b"
fi
;;
esac
done

Storing bash script argument with multiple values

I would like to be able to parse an input to a bash shell script that looks like the following.
myscript.sh --casename obstacle1 --output en --variables v P pResidualTT
The best I have so far fails because the last argument has multiple values. The first arguments should only ever have 1 value, but the third could have anything greater than 1. Is there a way to specify that everything after the third argument up to the next set of "--" should be grabbed? I'm going to assume that a user is not constrained to give the arguments in the order that I have shown.
casename=notset
variables=notset
output_format=notset
while [[ $# -gt 1 ]]
do
key="$1"
case $key in
--casename)
casename=$2
shift
;;
--output)
output_format=$2
shift
;;
--variables)
variables="$2"
shift
;;
*)
echo configure option \'$1\' not understood!
echo use ./configure --help to see correct usage!
exit -1
break
;;
esac
shift
done
echo $casename
echo $output_format
echo $variables
One conventional practice (if you're going to do this) is to shift multiple arguments off. That is:
variables=( )
case $key in
--variables)
while (( "$#" >= 2 )) && ! [[ $2 = --* ]]; do
variables+=( "$2" )
shift
done
;;
esac
That said, it's more common to build your calling convention so a caller would pass one -V or --variable argument per following variable -- that is, something like:
myscript --casename obstacle1 --output en -V=v -V=p -V=pResidualTT
...in which case you only need:
case $key in
-V=*|--variable=*) variables+=( "${1#*=}" );;
-V|--variable) variables+=( "$2" ); shift;;
esac

Bash - Wrapping another command's parameters

Wrapping another command's parameters
I have a command tool1 that parses arguments this way:
#!/usr/bin/env bash
# ...
while [[ $# -ge 1 ]]
do
key="$1"
case $key in
-o|--option)
OPT="$2"
shift
;;
-u|--user)
USR="$2"
shift
;;
-*)
echo -e "Unrecognized option: \"$key\"" && exit 1
;;
*)
OTHERS+=("$1")
;;
esac
shift
done
# ...
I have tool2 that calls tool1. Thus tool2 will have to pass parameters to tool1. It may also need to process the same parameters (--user)
tool2 looks like:
#!/usr/bin/env bash
# ...
while [[ $# -ge 1 ]]
do
key="$1"
case $key in
-O|--option2)
opt2="$2"
shift
;;
-u|--user)
USR="$2"
OTHERS+=("-u $2")
shift
;;
-*)
echo -e "Unrecognized option: \"$key\"" && exit 1
;;
*)
OTHERS+=("$1")
;;
esac
shift
done
## Call tool1 with other parameters to pass
bash tool1.sh ${OTHERS[#]}
# ...
To sum up
--option2 is an option used only by tool2.
--user is common to both tools, and may be used by tool2 too, before calling tool1.sh. Because of this, in this example --user has to be explicitly passed to tool1 thanks to the array OTHERS.
I'd like to know about possible and/or alternative ways of dealing with such parameter redundancies. A methodology that would help me wrapping another tool's expected parameters/options, without having to copy/paste the lines regarding the parsing of such redundant parameters/options.
tool2's approach is fine. However, you aren't setting OTHERS correctly.
-u|--user)
USR="$2"
OTHERS+=("-u" "$2")
shift
-u and its argument need to remain separate array elements, just as they were separate arguments to tool2. You also need to quote the expansion of OTHERS, to preserve arguments containing word-splitting characters or globs:
bash tool1.sh "${OTHERS[#]}"
Finally, all-uppercase variable names are reserved for use by the shell itself; don't define such names yourself. Just use others instead of OTHERS.

How to create a flag with getopts to run a command

I need help with my getopts, i want to be able to run this command ( mount command) only if i pass a flag ( -d in this case).
below output is what i have on my script but it doesn't seem to work.
CHECKMOUNT=" "
while getopts ":d" opt
do
case "$opt" in
d) CHECKMOUNT="true" ;;
usage >&2
exit 1;;
esac
done
shift `expr $OPTIND-1`
FS_TO_CHECK="/dev"
if [ "$CHECKMOUNT" = "true" ]
then
if cat /proc/mounts | grep $FS_TO_CHECK > /dev/null; then
# Filesystem is mounted
else
# Filesystem is not mounted
fi
fi
Your script has a number of problems.
Here is the minimal list of fixes to get it working:
While is not a bash control statement, it's while. Case is important.
Whitespace is important: if ["$CHECKMOUNT"= "true"] doesn't work and should cause error messages. You need spaces around the brackets and around the =, like so: if [ "$CHECKMOUNT" = "true" ].
Your usage of getopts is incorrect, I'm guessing that you mistyped this copying an example: While getopts :d: opt should be: while getopts ":d" opt.
Your usage of shift is incorrect. This should cause error messages. Change this to: shift $((OPTIND-1)) if you need to shift OPTIND.
The bare text unknocn flag seems like a comment, precede it with #, otherwise you'll get an error when using an unknown option.
There is no usage function. Define one, or change usage in your \?) case to an echo with usage instructions.
Finally, if your script only requires a single optional argument, you might also simply process it yourself instead of using getopt - the first argument to your script is stored in the special variable $1:
if [ "$1" = "-d" ]; then
CHECKMOUNT="true"
elif [ "$1" != "" ]; then
usage >&2
exit 1
fi

How to create a bash script that takes arguments?

I already know about getopts, and this is fine, but it is annoying that you have to have a flag even for mandatory arguments.
Ideally, I'd like to be able to have a script which receives arguments in this form:
script.sh [optional arguments] [anything required]
for example
script.sh -rvx output_file.txt
where the script says you HAVE to have an output file. Is there any easy way to do this?
As far as I know, with getopts it would have to look like: script.sh -rvx -f output_file.txt, and that is just not very clean.
I can also use python if necessary, but only have 2.4 available, which is a bit dated.
Don't use the getopts builtin, use getopt(1) instead. They are (subtly) different and do different things well. For you scenario you could do this:
#!/bin/bash
eval set -- $(getopt -n $0 -o "-rvxl:" -- "$#")
declare r v x l
declare -a files
while [ $# -gt 0 ] ; do
case "$1" in
-r) r=1 ; shift ;;
-v) v=1 ; shift ;;
-x) x=1 ; shift ;;
-l) shift ; l="$1" ; shift ;;
--) shift ;;
-*) echo "bad option '$1'" ; exit 1 ;;
*) files=("${files[#]}" "$1") ; shift ;;
esac
done
if [ ${#files} -eq 0 ] ; then
echo output file required
exit 1
fi
[ ! -z "$r" ] && echo "r on"
[ ! -z "$v" ] && echo "v on"
[ ! -z "$x" ] && echo "x on"
[ ! -z "$l" ] && echo "l == $l"
echo "output file(s): ${files[#]}"
EDIT: for completeness I have provided an example of handling an option requiring an argument.
If you are using getops, just shift by $OPTIND-1 after your case statement. Then what is left in $* will be everything else, which is probably what you want.
shift $(( ${OPTIND} - 1 )); echo "${*}"
You're are suffering from illusions; using getopts does not require mandatory arguments prefixed by a flag letter. I tried to find a suitable example from my corpus of scripts; this is a semi-decent approximation. It is called rcsunco and is used to cancel a checkout from RCS. I haven't modified it in a while, I see; I use it quite often (because I haven't migrated from RCS completely, yet).
#!/bin/sh
#
# "#(#)$Id: rcsunco.sh,v 2.1 2002/08/03 07:41:00 jleffler Exp $"
#
# Cancel RCS checkout
# -V print version number
# -n do not remove or rename checked out file (like SCCS unget) (default)
# -r remove checked out file (default)
# -k keep checked out file as $file.keep
# -g checkout (unlocked) file after clean-up
# -q quiet checkout
: ${RCS:=rcs}
: ${CO:=co}
remove=yes
keep=no
get=no
quiet=
while getopts gknqrV opt
do
case $opt in
V) echo "`basename $0 .sh`: RCSUNCO Version $Revision: 2.1 $ ($Date: 2002/08/03 07:41:00 $)" |
rcsmunger
exit 0;;
g) get=yes;;
k) keep=yes;;
n) remove=no;;
q) quiet=-q;;
r) remove=yes;;
*) echo "Usage: `basename $0 .sh` [-{n|g}][-{r|k}] file [...]" 1>&2
exit 1;;
esac
done
shift $(($OPTIND-1))
for file in $*
do
rfile=$(rfile $file)
xfile=$(xfile $rfile)
if $RCS -u $rfile
then
if [ $keep = yes ]
then
if [ -f $xfile ]
then
mv $xfile $xfile.keep
echo "$xfile saved in $xfile.keep"
fi
elif [ $remove = yes ]
then rm -f $xfile
fi
if [ $get = yes ] && [ $remove = yes -o $keep = yes ]
then $CO $quiet $rfile
fi
fi
done
It's only a semi-decent approximation; the script quietly does nothing if you don't supply any file names after the optional arguments. However, if you need to, you can check that the mandatory arguments are present after the 'shift'. Another script of mine does have mandatory arguments. It contains:
...
shift $(($OPTIND - 1))
case $# in
2) case $1 in
install) MODE=Installation;;
uninstall) MODE=Uninstallation;;
*) usage;;
esac;;
*) usage;;
esac
So, that command (jlss) can take optional arguments such as -d $HOME, but requires either install or uninstall followed by the name of something to install. The basic mode of use is:
jlss install program
But the optional mode is:
jlss -d $HOME -u me -g mine -x -p install program
I didn't show all of jlss because it has about 12 options - it isn't as compact as rcsunco.
If you were dealing with mandatory arguments before option arguments, then you'd have to do a bit more work:
You'd pick up the mandatory arguments, shifting them out of the way.
Then you process the optional arguments with the flags.
Finally, if appropriate, you handle the extra 'file name' arguments.
If you are dealing with mandatory arguments interspersed with option arguments (both before and after the mandatory ones), then you have still more work to do. This is used by many VCS systems; CVS and GIT both have the facility:
git -global option command [-sub option] [...]
Here, you run one getopts loop to get the global options; pick up the mandatory arguments; and run a second getopts loop to get the sub-options (and maybe run a final loop over the 'file name' arguments).
Isn't life fun?
And I heard a completely opposite thing, that you shouldn't use getopt, but the getopts builtin.
Cross-platform getopt for a shell script
Never use getopt(1). getopt cannot handle empty arguments strings, or
arguments with embedded whitespace. Please forget that it ever
existed.
The POSIX shell (and others) offer getopts which is safe to use
instead.
Here's yet another way to "Option-ize your shell scripts" (whithout using getopt or getopts):
http://bsdpants.blogspot.com/2007/02/option-ize-your-shell-scripts.html

Resources