Bash: processing arguments in a script when called from the shell

Read in Medium

Hi. In my spare time, I write a project for work purposes, which consists of a bunch of bash scripts. There is one entry point that connects the rest of the functionality via ‘source’. They contain functions that should only process the required arguments directly from the cli.

In early versions of the project, I just explicitly passed $1, $2, $N from top to bottom to other functions. It was a stupid solution, and it worked because the possible arguments and their order were known and simple. But it was disgusting aesthetically. I wanted to enjoy reading code and to unify a lot of things. To do this, the entire code had to be greatly complicated to make everything conceptually much simpler.

So, different functions must accept different arguments from input, and also I want to give to user an ability to pass:

  • long arguments with no values:
    ./ --foo --bar
  • long arguments with values:
    ./ --foo = bar
  • short arguments without values:
    ./ -a -b -c
  • short arguments with values:
    ./ -a avalue -b bvalue
  • combine any short short arguments into one word:
    ./ -abc bvalue
  • all of above ones at the same time!
  • the order of the arguments shouldn’t matter
  • I hould have access to any of them from anywhere at any time.
Categorized as blog-en Tagged