Improve your Bash scripts with Argbash

Do you write or maintain non-trivial bash scripts? If so, you probably want them to accept command-line arguments in a standard and robust way. Fedora recently got a nice addition which can help you produce better scripts. And don’t worry, it won’t cost you much of your time or energy.

Why Argbash?

Bash is an interpreted command-line language with no standard library. Therefore, if you write bash scripts and want command-line interfaces that conform to POSIX and GNU CLI standards, you’re used to only two options:

  1. Write the argument-parsing functionality tailored to your script yourself (possibly using the
    getopts

    builtin).

  2. Use an external bash module.

The first option looks incredibly silly as implementing the interface properly is not trivial. However, it is suggested as the best choice on various sites ranging from Stack Overflow to the Bash Hackers wiki.

The second option looks smarter, but using a module has its issues. The biggest is you have to bundle its code with your script. This may mean either:

  • You distribute the library as a separate file, or
  • You include the library code at the beginning of your script.

Having two files instead of one is awkward. So is polluting your bash scripts with a chunk of complex code over thousand lines long.

This was the main reason why the Argbash project came to life. Argbash is a code generator, so it generates a tailor-made parsing library for your script. Unlike the generic code of other bash modules, it produces minimal code your script needs. Moreover, you can request even simpler code if you don’t need 100% conformance to these CLI standards.

Example

Analysis

Let’s say you want to implement a script that draws a bar across the terminal window. You do that by repeating a single character of your choice multiple times. This means you need to get the following information from the command-line:

  • The character which is the element of the line. If not specified, use a dash. On the command-line, this would be a single-valued positional argument character with a default value of -.
  • Length of the line. If not specified, go for 80. This is a single-valued optional argument –length with a default of 80.
  • Verbose mode (for debugging). This is a boolean argument verbose, off by default.

As the body of the script is really simple, this article focuses on getting the input of the user from the command-line to appropriate script variables. Argbash generates code that saves parsing results to shell variables _arg_character, _arg_length and _arg_verbose.

Execution

In order to proceed, you need the argbash-init and argbash bash scripts that are parts of the argbash package. Therefore, run this command:

sudo dnf install argbash

Then, use argbash-init to generate a template for argbash, which generates the executable script. You want three arguments: a positional one called character, an optional length and an optional boolean verbose. Tell this to argbash-init, and then pass the output to argbash:

argbash-init --pos character --opt length --opt-bool verbose script-template.sh
argbash script-template.sh -o script
./script

See the help message? Looks like the script doesn’t know about the default option for the character argument. So take a look at the Argbash API, and then fix the issue by editing the template section of the script:

# ...
# ARG_OPTIONAL_SINGLE([length],[l],[Length of the line],[80])
# ARG_OPTIONAL_BOOLEAN([verbose],[V],[Debug mode])
# ARG_POSITIONAL_SINGLE([character],[The element of the line],[-])
# ARG_HELP([The line drawer])
# ...

Argbash is so smart that it tries to make every generated script a template of itself. This means you don’t have to worry about storing source templates for further use. You just shouldn’t lose your generated bash scripts. Now, try to regenerate the future line drawer to work as expected:

argbash script -o script
./script

As you can see, everything is working all right. The only thing left to do is fill in the line drawing functionality itself.

Conclusion

You might find the section containing parsing code quite long, but consider that it allows you to call ./script.sh x -Vl50 and it will be understood the same way as ./script -V -l 50 x. It does require some code to get this right.

However, you can shift the balance between generated code complexity and parsing abilities towards more simple code by calling argbash-init with argument –mode set to minimal. This option reduces the size of the script by about 20 lines, which corresponds to a roughly 25% decrease of the generated parsing code size. On the other hand, the full mode makes the script even smarter.

If you want to examine the generated code, give argbash the argument –commented, which puts comments into the parsing code that reveal the intent behind various sections. Compare that to other argument parsing libraries such as shflags, argsparse or bash-modules/arguments, and you’ll see the powerful simplicity of Argbash. If something goes horribly wrong and you need to fix a glitch in the parsing functionality quickly, Argbash allows you to do that as well.

As you’re most likely a Fedora user, you can enjoy the luxury of having command-line Argbash installed from the official repositories. However, there is also an online parsing code generator at your service. Furthermore, if you’re working on a server with Docker, you can appreciate the Argbash Docker image.

So enjoy and make sure that your scripts have a command-line interface that pleases your users. Argbash is here to help, with minimal effort required from your side.

For Developers For System Administrators New in Fedora

4 Comments

  1. aaa

    Where are the times where shell scripts had to be POSIX compatible and people were avoiding bahsizms?

    • rexxor

      strict posix ? But it is a small parody for posix standard in Bash, then I use Shellcheck + Dash to write scripts without HERE DOC and double brackets in TEST etc. 😉

  2. taikedz

    I must say, this seems horribly unwieldy… My personal take is that the way to better bash scripting is to start providing tooling that helps reduce its idiosyncrasies, not compound them…

    Generating templates that need post-processing, and generating heaps of caps’d variables to hunt down before they can be used, does not strike me as particularly friendly…

    I’ve been working on a tool to try to make bash more usable, in similar manner as any other scripting language, by means of a build tool… My bash scripts really have started looking like normal code since…!

    https://github.com/taikedz/bash-builder/

  3. Did you forgot to activate the copr or was it already enabled?

    [a@b ~]$ sudo dnf install argbash
    Failed to synchronize cache for repo ‘home_zhonghuaren’, wird deaktiviert.
    Letzte Prüfung auf abgelaufene Metadaten: vor 0:00:04 am Thu Dec 14 07:58:30 2017.
    Kein Paket argbash verfügbar.
    Fehler: Es konnte kein Treffer gefunden werden.

    [a@b ~]$ sudo dnf copr enable sgallagh/argbash

    [a@b ~]$ sudo dnf install argbash

    Copr repo for argbash owned by sgallagh 1.1 kB/s | 1.4 kB 00:01
    Failed to synchronize cache for repo ‘home_zhonghuaren’, wird deaktiviert.

    Abhängigkeiten sind aufgelöst.

    Package Arch Version Paketquelle Größe

    Installieren:
    argbash noarch 2.3.0-0.1.fc25 sgallagh-argbash 37 k

    Transaktionsübersicht

    Installieren 1 Paket

    Gesamte Downloadgröße: 37 k
    Installationsgröße: 100 k
    Ist dies in Ordnung? [j/N]:

Comments are Closed

The opinions expressed on this website are those of each author, not of the author's employer or of Red Hat. Fedora Magazine aspires to publish all content under a Creative Commons license but may not be able to do so in all cases. You are responsible for ensuring that you have the necessary permission to reuse any work on this site. The Fedora logo is a trademark of Red Hat, Inc. Terms and Conditions