Bash - Wrapping another command's parameters - bash

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.

Related

Bash - Best way to have helpFunction & default parameter values

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.

Automatic parsing of getopts options into dynamic variables of same name in bash

I have a bash script I wrote with say, 3 command line options, bib, bob and boo... and I want to read in the user options into a bash variable of the same name, which I do as follows:
PARSED_OPTIONS=$(getopt -n $0 --long "bib:,bob:,boo:" -- "$#")
eval set -- "$PARSED_OPTIONS";
while true; do
case "$1" in
--bib)
bib=$2
shift 2;;
--bob)
bob=$2
shift 2;;
--boo)
boo=$2
shift 2 ;;
--)
shift
break;;
esac
done
This all works fine, so far, so good...
But now I want to extend this to a list of many many options, and so rather than writing out a long case statement, it would be really nice to be able to somehow loop over a list of options and automatically pass the options to the variable, something along these lines
opts="bib:,bob:,boo:,"
PARSED_OPTIONS=$(getopt -n $0 --long $opts -- "$#")
for arg in `echo $opts | tr , " "` ; do
eval set -- "$PARSED_OPTIONS";
while true; do
case "$1" in
--${arg})
declare $arg=$2
shift 2
;;
--)
shift
break;;
esac
done
done
I'm using the declaration statement to get the argument into a dynamic variable of the same name (see Dynamic variable names in Bash second solution), and this solution to do the loop over comma separated lists Loop through a comma-separated shell variable but I'm getting an infinite loop here. I think because the 2 unused options are allows as they are in the PARSED_OPTIONS list, but then they are not sliced off in the loop as only "arg" is looked for... I can't see an obvious way around this, but I'm sure there is one.
I realized that I had the shift command still inside the case statement, so that is why it wasn't exiting. I also needed to strip the colon : from the argument, so here is my automated argument retrieval for a bash script that works:
# specify an arbitrary list of arguments:
opts=bib:,bob:,boo:
PARSED_OPTIONS=$(getopt -n $0 --long "${opts}" -- "$#")
for arg in ${opts//,/ } ; do
var=${arg//:} # remove the colon
eval set -- "$PARSED_OPTIONS";
while true ; do
case "$1" in
--${var})
declare ${var}=$2
;;
--)
break
;;
esac
shift 2
done
done
So if you try test_script --boo 3 --bib hello --bob lkkfrfrfr
echo $bib $bob $boo
should give
hello lkkfrfrfr 3

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

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

Escape accumulated arguments in a shell script?

With a view to a bug in git, at the moment git-submodule.sh reads (reordered):
[iterating over command line arguments]
--reference)
case "$2" in '') usage ;; esac
reference="--reference=$2"
shift
;;
--reference=*)
reference="$1"
shift
;;
[...]
if test -n "$reference"
then
git-clone $quiet "$reference" -n "$url" "$path" --separate-git-dir "$gitdir"
else
git-clone $quiet -n "$url" "$path" --separate-git-dir "$gitdir"
fi ||
die "$(eval_gettext "Clone of '\$url' into submodule path '\$path' failed")"
This uses only the last argument given by --reference. I now want to enhance this so that all --reference options are passed on to git-clone. This is trivial for trivial arguments (reference="$reference --reference=$2"), but my mind boggles when thinking about arguments containing white space, quote or shell meta characters.
What is the best practice to escape such accumulated arguments?
Best practice would be to use a bash array:
declare -a references
#...
--reference)
case ... esac
references+=("--reference=$2")
shift
;;
--reference=*)
references+=("$1")
shift
;;
#...
# no need to test the array for emptiness
git-clone $quiet "${references[#]}" -n "$url" "$path" --separate-git-dir "$gitdir"
However, the referenced script uses /bin/sh instead.

Resources