TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Argbash – Bash Argument Parsing Code Generator

102 pointsby quincepieabout 2 years ago

17 comments

databasherabout 2 years ago
Handling command-line arguments in Bash is easy. Bash&#x27;s `getopts` handles short and long arguments gnu-style without any problem, out of the box, without any need for libraries or complicated packages.<p>This pattern handles lots of styles of options: short and long options (-h, --help), `--` for separating options from positional args, with GNU-style long options (--output-file=$filename).<p><pre><code> while getopts :o:h-: option do case $option in h ) print_help;; o ) output_file=$OPTARG;; - ) case $OPTARG in help ) print_help;; output-file=* ) output_file=${OPTARG##*=};; * ) echo &quot;bad option $OPTARG&quot; &gt;&amp;2; exit 1;; esac;; &#x27;?&#x27; ) echo &quot;unknown option: $OPTARG&quot; &gt;&amp;2; exit 1;; : ) echo &quot;option missing argument: $OPTARG&quot; &gt;&amp;2; exit 1;; * ) echo &quot;bad state in getopts&quot; &gt;&amp;2; exit 1;; esac done shift $((OPTIND-1)) (( $# &gt; 0 )) &amp;&amp; printf &#x27;remaining arg: %s\n&#x27; &quot;$@&quot;</code></pre>
评论 #35241670 未加载
评论 #35238993 未加载
feisuzhuabout 2 years ago
I&#x27;ve found that every time my bash scripts become sufficiently complex, I end up rewriting them in Python.
评论 #35237189 未加载
评论 #35235478 未加载
评论 #35237438 未加载
评论 #35234317 未加载
评论 #35236410 未加载
评论 #35237046 未加载
评论 #35243330 未加载
评论 #35241109 未加载
评论 #35235103 未加载
ndsipa_pomuabout 2 years ago
I&#x27;m a fan of BashBoilerPlate (Bash3BoilerPlate) - <a href="https:&#x2F;&#x2F;github.com&#x2F;xwmx&#x2F;bash-boilerplate">https:&#x2F;&#x2F;github.com&#x2F;xwmx&#x2F;bash-boilerplate</a><p>It uses a similar style of deriving the arguments from the usage declaration, but it also includes some useful logging functions and is all in one script. There&#x27;s some more info available on their style choices here: <a href="https:&#x2F;&#x2F;bash3boilerplate.sh&#x2F;" rel="nofollow">https:&#x2F;&#x2F;bash3boilerplate.sh&#x2F;</a>
评论 #35241066 未加载
chrsigabout 2 years ago
I really wish bash could evolve...in particular around control flow, variable assignment, string interpolation, and arithmetic.<p>I love working with bash, but it has some footguns that really require an expert hand.<p>I know bash as-is will always be around for backwards compatibility with the god-knows-how-many scripts out there. It&#x27;d just be nice if there were a widely embraced path forward that kept the shell scripting spirit while shedding some of the unintuitive behaviors
评论 #35234534 未加载
评论 #35237500 未加载
评论 #35236931 未加载
评论 #35240854 未加载
shaftwayabout 2 years ago
I&#x27;ve always assumed that there was some argument parser available that just sets things as environment variables, and that my google-fu is just too weak to find it.<p>Why ccouldn&#x27;t I just go `source argbash _ARG_ --single option o --bool print --position positional -- $@` and get _ARG_OPTION, _ARG_PRINT, and _ARG_POSITIONAL environment variables set based on the commands passed in, without having to dump a hundred lines of code in my script?
tpoacherabout 2 years ago
Am I the only one who finds argbash unnecessarily complicated?<p>For my own needs, I rely on a tiny function I wrote, called process_optargs. Example use:<p><pre><code> source &#x2F;path&#x2F;to&#x2F;process_optargs source &#x2F;path&#x2F;to&#x2F;error source &#x2F;path&#x2F;to&#x2F;is_in function myfunction () { # example function whose options&#x2F;arguments we&#x27;d want to process # Define local variables which will be populated or checked against inside process_optargs local -A OPTIONS=() local -a ARGS=() local -a VALID_FLAG_OPTIONS=( -h&#x2F;--help -v --version ) # note -v and --version represent separate flags here! (e.g. &#x27;-v&#x27; could be for &#x27;verbose&#x27;) local -a VALID_KEYVAL_OPTIONS=( -r&#x2F;--repetitions ) local COMMAND_NAME=&quot;myfunction&quot; # Process options and arguments; exit if an error occurs process_optargs &quot;$@&quot; || exit 1 # Validate and collect parsed options and arguments as desired if is_in &#x27;-h&#x27; &quot;${!OPTIONS[@]}&quot; || is_in &#x27;--help&#x27; &quot;${!OPTIONS[@]}&quot; then display_help fi if is_in &#x27;-r&#x27; &quot;${!OPTIONS[@]}&quot;; then REPS=&quot;${OPTIONS[-r]}&quot; elif is_in &#x27;--repetitions&#x27; &quot;${!OPTIONS[@]}&quot;; then REPS=&quot;${OPTIONS[--repetitions]}&quot; fi if test &quot;${#ARGS[@]}&quot; -lt 2 then error &quot;myfunction requires at least 2 non-option arguments&quot; exit 1 fi # ...etc } </code></pre> It works as you&#x27;d expect, with appropriate checks for correctness of inputs, and is compatible with most unix conventions (including &#x27;--&#x27; and &#x27;-&#x27; as arguments).<p>If anyone&#x27;s interested let me know and I can share the code.
评论 #35241954 未加载
softskunkabout 2 years ago
as cool as this is, i feel that anything with the complexity of more than one or two arguments should really be written in a different language, like Python (or AppleScript for macOS users). bash just isn’t the right tool for the job then.
评论 #35234567 未加载
nadavivabout 2 years ago
GPT is pretty good at figuring out argument parsing code based on example CLI usage. Like this:<p><pre><code> &gt; Write bash code to parse the following arguments: &gt; &gt; $ .&#x2F;export.sh --out-file dump.json --db foo.sqlite --include-headers --exclude-rev -vvv -p9000 Here&#x27;s an example bash code to parse the arguments: #!&#x2F;bin&#x2F;bash # Default values for optional arguments INCLUDE_HEADERS=false EXCLUDE_REV=false VERBOSE_LEVEL=0 PORT=0 # Parse the arguments while [[ &quot;$#&quot; -gt 0 ]]; do case $1 in --out-file) OUT_FILE=&quot;$2&quot;; shift ;; --db) DB=&quot;$2&quot;; shift ;; --include-headers) INCLUDE_HEADERS=true ;; --exclude-rev) EXCLUDE_REV=true ;; -v) VERBOSE_LEVEL=$((VERBOSE_LEVEL+1)) ;; -p) PORT=&quot;$2&quot;; shift ;; -h|--help) echo &quot;Usage: .&#x2F;export.sh [OPTIONS]&quot; echo &quot;&quot; echo &quot;Options:&quot; echo &quot;--out-file Output file path (required)&quot; echo &quot;--db Database path (required)&quot; echo &quot;--include-headers Include column headers in output (default: false)&quot; echo &quot;--exclude-rev Exclude revisions in output (default: false)&quot; echo &quot;-v Increase verbosity level (default: 0)&quot; echo &quot;-p Port number (default: 0)&quot; echo &quot;-h, --help Show help&quot; exit 0 ;; *) echo &quot;Unknown parameter passed: $1&quot;; exit 1 ;; esac shift done # Check required arguments if [[ -z $OUT_FILE ]]; then echo &quot;Error: missing argument --out-file&quot; exit 1 fi if [[ -z $DB ]]; then echo &quot;Error: missing argument --db&quot; exit 1 fi # Print parsed arguments echo &quot;OUT_FILE=$OUT_FILE&quot; echo &quot;DB=$DB&quot; echo &quot;INCLUDE_HEADERS=$INCLUDE_HEADERS&quot; echo &quot;EXCLUDE_REV=$EXCLUDE_REV&quot; echo &quot;VERBOSE_LEVEL=$VERBOSE_LEVEL&quot; echo &quot;PORT=$PORT&quot;</code></pre>
评论 #35237969 未加载
评论 #35240345 未加载
simonwabout 2 years ago
Languages that I work with infrequently enough to remember how to use them - like Bash - are the absolute perfect place to apply LLM tech like ChatGPT.<p>Prompt:<p>&gt; Write a bash script &quot;foo.sh&quot; that accepts a required filename, optional flags for &quot;-r&#x2F;--reverse&quot; and &quot;-s&#x2F;--skip&quot; and an optional &quot;-o&#x2F;--output=other-file&quot; parameter. It should have &quot;-h&#x2F;--help&quot; text too explaining this.<p>Then copy and paste out the result and write the rest of the script (or use further prompts to get ChatGPT to write it for you).<p>Could it be done better if I spent more time on it or was a Bash expert? Absolutely, but for most of the times when I need to do something like this I really don&#x27;t care too much about the finished quality.
sacnoradhqabout 2 years ago
Cute and lots of effort went into this, but code generation is, unfortunately, unmaintainable and inflexible. This seems targeted at users who want to avoid mastery of their tools, which is fine for some.<p>util-linux getopt exists.
iamjackgabout 2 years ago
This is very similar to Bashly (<a href="https:&#x2F;&#x2F;bashly.dannyb.co&#x2F;" rel="nofollow">https:&#x2F;&#x2F;bashly.dannyb.co&#x2F;</a>) but with a lot more weird magic going on.
nickjjabout 2 years ago
If anyone is looking for a snippet to handle both positional args along with required and optional flags (both with short and long form formats) along with basic validation I put together: <a href="https:&#x2F;&#x2F;nickjanetakis.com&#x2F;blog&#x2F;parse-command-line-positional-arguments-and-flags-with-bash" rel="nofollow">https:&#x2F;&#x2F;nickjanetakis.com&#x2F;blog&#x2F;parse-command-line-positional...</a>, it includes the source code annotated with comments and a demo video.
tveybenabout 2 years ago
I have great pleasure when using docopt in Python.<p>I see docopts is ‘the same’ implementation but for shell, have never tried it though.<p>==== docopt helps you:<p>- define the interface for your command-line app, and - automatically generate a parser for it. ====<p><a href="http:&#x2F;&#x2F;docopt.org&#x2F;" rel="nofollow">http:&#x2F;&#x2F;docopt.org&#x2F;</a><p><a href="https:&#x2F;&#x2F;github.com&#x2F;docopt&#x2F;docopts">https:&#x2F;&#x2F;github.com&#x2F;docopt&#x2F;docopts</a>
akhoabout 2 years ago
Yet another point where Fish is a delight.<p>Going to Python&#x2F;whatever is not quite the same — shell scripts are not as much written as extracted from shell history, so switching to a separate language is a large extra step.
rickydrollabout 2 years ago
I have used are – for many projects and it is wonderful. But as others have indicated, be mindful of whether or not Bash is the right tool for the task at hand.
评论 #35233993 未加载
caymanjimabout 2 years ago
What&#x27;s with:<p><pre><code> # [ &lt;-- needed because of Argbash </code></pre> There&#x27;s also this bit:<p><i>The square brackets in your script have to match (i.e. every opening square bracket [ has to be followed at some point by a closing square bracket ]).<p>There is a workaround — if you need constructs s.a. red=$&#x27;\e[0;91m&#x27;, you can put the matching square bracket behind a comment, i.e. red=$&#x27;\e[0;91m&#x27; # match square bracket: ].</i><p>That kind of kludginess is a turn-off.
评论 #35241090 未加载
Joker_vDabout 2 years ago
Huh, it uses M4 to build its DSL, how quaint.<p>I wish there were more projects on the other side of the spectrum: take the script&#x27;s self-reported usage string, à la docopt [0], and derive argument-parsing code from <i>that</i>. After all, we have GPT-4 now.<p>[0] <a href="https:&#x2F;&#x2F;github.com&#x2F;docopt&#x2F;docopts">https:&#x2F;&#x2F;github.com&#x2F;docopt&#x2F;docopts</a>