A shell argparse tool based on python argparse module.
- python >= 3 is required;
- Download the script
parseopt.py
to any of your directory.
In the shell script, add parser information as in python. e.g.
python-styled parser
...
parser.add_argument("input", type=str, help="Input file.")
parser.add_argument("-o", "--output", type=str, default="${input}_out",
help="Output file. Default: <input>_out")
shell parser test.sh
<<"PARSER"
("input", type=str, help="Input file.")
("-o", "--output", type=str, default="${input}_out",
help="Output file. Default: <input>_out")
PARSER
opts=$(python parseopt.py $0 $*) && eval $opts || exit 1
Now have a try
$ bash test.sh
usage: test.sh [-h] [-o OUTPUT] input
test.sh: error: the following arguments are required: input
$ bash test.sh -h
usage: test.sh [-h] [-o OUTPUT] input
positional arguments:
input Input file.
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
Output file. Default: <input>_out
Just in case if you're interested in the implementation. Here is the process
$(python parseopt.py $0 $*)
command run the python script in the shell script,$0
is the name of the script (test.sh
here);$*
indicate all arguments passed totest.sh
(such as-h
)- In
parseopt.py
, the program searches for control flags<<"PARSER"
andPARSER
, which represent the start and the end of argument parser respectively, and return the wrapped content to the next step. - The program searches bracket pairs
()
to get the argument parser string. Python interpreter functioneval
is used to resolve the strings and build the parser. - Then all arguments (passed by
$*
) are resolved by the parser, which tells if there is any missing positional argument, unknown option or-h, --help
. - If no error is raised at step 4, the python script writes arguments and their values to the
sys.stdout
aswhich is then assigned to shell variableexport input=<input>; export output=<output>; ...
$opts
eval $opts
in shell scripts sets up all the arguments, so them can be used in following lines.