Jay Taylor's notes

back to listing index

Python argument parsing for bash scripts

[web search]
Original source (gist.github.com)
Tags: python bash flag-parsing argparse horrifying-yet-awesome sweet-spot gist.github.com
Clipped on: 2020-12-17

Python argument parsing for bash scripts
1 #!/bin/sh
2
3 # This is free and unencumbered software released into the public domain.
4 #
5 # Anyone is free to copy, modify, publish, use, compile, sell, or
6 # distribute this software, either in source code form or as a compiled
7 # binary, for any purpose, commercial or non-commercial, and by any
8 # means.
9 #
10 # In jurisdictions that recognize copyright laws, the author or authors
11 # of this software dedicate any and all copyright interest in the
12 # software to the public domain. We make this dedication for the benefit
13 # of the public at large and to the detriment of our heirs and
14 # successors. We intend this dedication to be an overt act of
15 # relinquishment in perpetuity of all present and future rights to this
16 # software under copyright law.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21 # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
22 # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23 # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 # OTHER DEALINGS IN THE SOFTWARE.
25 #
26 # For more information, please refer to <https://unlicense.org>
27
28 VARS=$(python3 - "$@" << EOF
29 import argparse
30 import shlex
31 parser = argparse.ArgumentParser(prog="$0")
32
33 # Add arguments here
34 # parser.add_argument('--foo-bar')
35
36 args = parser.parse_args()
37 for k, v in vars(args).items():
38 print("{}={}".format(k, shlex.quote(str(v))))
39 EOF
40 )
41 if echo "$VARS" | grep -q "^usage:"; then
42 echo "$VARS"
43 exit 1
44 fi
45 eval $VARS
46
47 # use arguments here
48 # echo "$foo_bar"
Image (Asset 2/3) alt= Add header text Add bold text <ctrl+b> Add italic text <ctrl+i>
Insert a quote Insert code Add a link <ctrl+k>
Add a bulleted list Add a numbered list Add a task list
Directly mention a user or team Reference an issue or pull request
Attach files by dragging & dropping, selecting or pasting them. Styling with Markdown is supported