<p>If you are writing a program that is executable from the command line, you often want to offer the user several options or flags, along with possibly more than one argument. I have stumbled my way through this many times, but is there some sort of design pattern for looping through args and calling the appropriate handler functions?</p>

<p>Consider:</p>

<pre><code>myprogram -f filename -d directory -r regex
</code></pre>

<p>How do you organize the handler functions after you retrieve the arguments using whatever built-ins for your language? (language-specific answers welcomed, if that helps you articulate an answer)</p>

[{'answer_id': 54457, 'author': 'Peter Ritchie', 'author_id': 5620, 'author_profile': 'https://Stackoverflow.com/users/5620', 'pm_score': 5, 'selected': True, 'text': '<p>I don\'t know of any documented "patterns" for processing.</p>\n\n<p>I believe one of the oldest libraries/APIs for handling arguments is getopt.  Googling "getopt" shows lots of man pages and links to implementations.</p>\n\n<p>Generally, I have a preferences or settings service in my application that the argument processor knows how to communicate with.  Arguments are then translated into something in this service that the application than then query.  This could be as simple as a dictionary of settings (like a string setting named "filename").</p>\n'}, {'answer_id': 54460, 'author': 'Kilhoffer', 'author_id': 5469, 'author_profile': 'https://Stackoverflow.com/users/5469', 'pm_score': 1, 'selected': False, 'text': '<p>I would recommend using a command line processor library. <a href="http://netcode.ru/dotnet/?lang=&amp;katID=30&amp;skatID=268&amp;artID=7379" rel="nofollow noreferrer">Some Russian guy</a> created a decent one, but there are tons of them out there. Will save you some time so you can concentrate on the purpose of your app rather than parsing command line switches!</p>\n'}, {'answer_id': 54464, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 3, 'selected': False, 'text': '<p>You didn\'t mention the language, but for Java we\'ve loved <a href="http://commons.apache.org/cli/" rel="noreferrer">Apache Commons CLI</a>.  For C/C++, getopt.</p>\n'}, {'answer_id': 54479, 'author': 'Dave Verwer', 'author_id': 4496, 'author_profile': 'https://Stackoverflow.com/users/4496', 'pm_score': 0, 'selected': False, 'text': '<p>You don\'t mention a language for this but if you are looking for a really nice Objective-C wrapper around getopt then Dave Dribin\'s DDCLI framework is really nice.</p>\n\n<p><a href="http://www.dribin.org/dave/blog/archives/2008/04/29/ddcli" rel="nofollow noreferrer">http://www.dribin.org/dave/blog/archives/2008/04/29/ddcli</a></p>\n'}, {'answer_id': 54480, 'author': 'Xetius', 'author_id': 274, 'author_profile': 'https://Stackoverflow.com/users/274', 'pm_score': 0, 'selected': False, 'text': '<p>I use the <a href="http://perldoc.perl.org/Getopt/Std.html" rel="nofollow noreferrer">Getopts::std</a> and <a href="http://perldoc.perl.org/Getopt/Long.html" rel="nofollow noreferrer">Getopts::long</a> in perl and also the <a href="http://www.gnu.org/software/libc/manual/html_node/Getopt.html#Getopt" rel="nofollow noreferrer">Getopt</a> function in C.  This standardises the parsing and format of parameters.  Other languages have different mechanisms for handling these.</p>\n\n<p>Hope this helps</p>\n'}, {'answer_id': 54481, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 0, 'selected': False, 'text': '<p>The standard design usually follows what getopt does, there are getopt libraries for many languages, .NET, python, C, Perl, PHP, etc.</p>\n\n<p>The basic design is to have a command line parser which returns part by part the arguments passed to be checked in a loop.</p>\n\n<p><a href="http://www-128.ibm.com/developerworks/aix/library/au-unix-getopt.html" rel="nofollow noreferrer">This</a> article discusses it in some more detail.</p>\n'}, {'answer_id': 54491, 'author': 'cfeduke', 'author_id': 5645, 'author_profile': 'https://Stackoverflow.com/users/5645', 'pm_score': 1, 'selected': False, 'text': '<p>Getopt is the only way to go.</p>\n\n<p><a href="http://sourceforge.net/projects/csharpoptparse" rel="nofollow noreferrer">http://sourceforge.net/projects/csharpoptparse</a></p>\n'}, {'answer_id': 54543, 'author': 'argv0', 'author_id': 5595, 'author_profile': 'https://Stackoverflow.com/users/5595', 'pm_score': 2, 'selected': False, 'text': '<p>The <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/program_options.html" rel="nofollow noreferrer">boost::program_options</a> library is nice if you\'re in C++ and have the luxury of using Boost.</p>\n'}, {'answer_id': 54690, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 2, 'selected': False, 'text': '<p>Assuming you have a "config" object that you aim to setup with the flags and a suitable command line parser that takes care of parsing the command line and supply a constant stream of the options, here goes a block of pseudocode</p>\n\n<pre><code>while (current_argument = cli_parser_next()) {\n    switch(current_argument) {\n        case "f": //Parser strips the dashes\n        case "force":\n            config-&gt;force = true;\n            break;\n        case "d":\n        case "delete":\n            config-&gt;delete = true;\n            break;\n        //So on and so forth\n        default:\n            printUsage();\n            exit;\n    }\n}\n</code></pre>\n'}, {'answer_id': 54883, 'author': 'Martin Del Vecchio', 'author_id': 5397, 'author_profile': 'https://Stackoverflow.com/users/5397', 'pm_score': 2, 'selected': False, 'text': '<p>I prefer options like "-t text" and "-i 44"; I don\'t like "-fname" or "--very-long-argument=some_value".</p>\n\n<p>And "-?", "-h", and "/h" all produce a help screen.</p>\n\n<p>Here\'s how my code looks:</p>\n\n<pre><code>int main (int argc, char *argv[])\n   {  int i;\n      char *Arg;\n      int ParamX, ParamY;\n      char *Text, *Primary;\n\n   // Initialize...\n   ParamX = 1;\n   ParamY = 0;\n   Text = NULL;\n   Primary = NULL;\n\n   // For each argument...\n   for (i = 0; i &lt; argc; i++)\n      {\n      // Get the next argument and see what it is\n      Arg = argv[i];\n      switch (Arg[0])\n         {\n         case \'-\':\n         case \'/\':\n            // It\'s an argument; which one?\n            switch (Arg[1])\n               {\n               case \'?\':\n               case \'h\':\n               case \'H\':\n                  // A cry for help\n                  printf ("Usage:  whatever...\\n\\n");\n                  return (0);\n                  break;\n\n               case \'t\':\n               case \'T\':\n                  // Param T requires a value; is it there?\n                  i++;\n                  if (i &gt;= argc)\n                     {\n                     printf ("Error:  missing value after \'%s\'.\\n\\n", Arg);\n                     return (1);\n                     }\n\n                  // Just remember this\n                  Text = Arg;\n\n                  break;\n\n               case \'x\':\n               case \'X\':\n                  // Param X requires a value; is it there?\n                  i++;\n                  if (i &gt;= argc)\n                     {\n                     printf ("Error:  missing value after \'%s\'.\\n\\n", Arg);\n                     return (1);\n                     }\n\n                  // The value is there; get it and convert it to an int (1..10)\n                  Arg = argv[i];\n                  ParamX = atoi (Arg);\n                  if ((ParamX == 0) || (ParamX &gt; 10))\n                     {\n                     printf ("Error:  invalid value for \'%s\'; must be between 1 and 10.\\n\\n", Arg);\n                     return (1);\n                     }\n\n                  break;\n\n               case \'y\':\n               case \'Y\':\n                  // Param Y doesn\'t expect a value after it\n                  ParamY = 1;\n                  break;\n\n               default:\n                  // Unexpected argument\n                  printf ("Error:  unexpected parameter \'%s\'; type \'command -?\' for help.\\n\\n", Arg);\n                  return (1);\n                  break;\n               }\n\n            break;\n\n         default:\n            // It\'s not a switch that begins with \'-\' or \'/\', so it\'s the primary option\n            Primary = Arg;\n\n            break;\n         }\n      }\n\n   // Done\n   return (0);\n   }\n</code></pre>\n'}, {'answer_id': 78034, 'author': 'mes5k', 'author_id': 1359466, 'author_profile': 'https://Stackoverflow.com/users/1359466', 'pm_score': 2, 'selected': False, 'text': '<p>A few comments on this...</p>\n\n<p>First, while there aren\'t any patterns per se, writing a parser is essentially a mechanical exercise, since given a grammar, a parser can be easily generated.  Tools like Bison, and ANTLR come to mind.</p>\n\n<p>That said, parser generators are usually overkill for the command line.  So the usual pattern is to write one yourself (as others have demonstrated) a few times until you get sick of dealing with the tedious detail and find a library to do it for you.  </p>\n\n<p>I wrote one for C++ that saves a bunch of effort that getopt imparts and makes nice use of templates: <a href="http://tclap.sourceforge.net" rel="nofollow noreferrer"><code>TCLAP</code></a></p>\n'}, {'answer_id': 111359, 'author': 'David Robbins', 'author_id': 19799, 'author_profile': 'https://Stackoverflow.com/users/19799', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m riffing on the ANTLR answer by mes5k.  This <a href="http://www.codeproject.com/KB/recipes/sota_expression_evaluator.aspx" rel="nofollow noreferrer">link to Codeproject</a> is for an article that discusses ANLTR and using the visit pattern to implement the actions you want you app to take.  It\'s well written and worth reviewing.</p>\n'}, {'answer_id': 7529952, 'author': 'Lindsay Morsillo', 'author_id': 945525, 'author_profile': 'https://Stackoverflow.com/users/945525', 'pm_score': 4, 'selected': False, 'text': '<p>I think the following answer is more along the lines of what you are looking for:</p>\n\n<p>You should look at applying the Template Pattern (Template Method in "Design Patterns" [Gamma, el al]) </p>\n\n<p>In short it\'s overall processing looks like this:</p>\n\n<pre><code>If the arguments to the program are valid then\n    Do necessary pre-processing\n    For every line in the input\n        Do necessary input processing\n    Do necessary post-processing\nOtherwise\n    Show the user a friendly usage message\n</code></pre>\n\n<p>In short, implement a ConsoleEngineBase class that has methods for:</p>\n\n<pre><code>PreProcess()\nProcessLine()\nPostProcess()\nUsage()\nMain()\n</code></pre>\n\n<p>Then create a chassis, that instantiates a ConsoleEngine() instance and sends the Main() message to kick it off.</p>\n\n<p>To see a good example of how to apply this to a console or command line program check out the following link:\n<a href="http://msdn.microsoft.com/en-us/magazine/cc164014.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/magazine/cc164014.aspx</a></p>\n\n<p>The example is in C#, but the ideas are easily implemented in any other environment.</p>\n\n<p>You would look at the GetOpt() as just the part that fit\'s into the argument handling (pre-processing).</p>\n\n<p>Hope this helps.</p>\n'}, {'answer_id': 23583280, 'author': 'amarnath chatterjee', 'author_id': 1178966, 'author_profile': 'https://Stackoverflow.com/users/1178966', 'pm_score': 3, 'selected': False, 'text': '<p>Well, its an old post but i would still like to contribute. The question was intended on choice of design patterns however i could see a lot of discussion on which library to use. I have checked out microsoft link as per lindsay which talks about template design pattern to use.</p>\n\n<p>However, i am not convinced with the post. Template pattern\'s intent is to define a template which will be implemented by various other classes to have uniform behavior. I don\'t think parsing command line fits into it. </p>\n\n<p>I would rather go with "Command" design pattern. This pattern is best fit for menu driven options.</p>\n\n<p><a href="http://www.blackwasp.co.uk/Command.aspx" rel="noreferrer">http://www.blackwasp.co.uk/Command.aspx</a></p>\n\n<p>so in your case, -f, -d and -r all becomes commands which has common or separate receiver defined. That way more receivers can be defined in future. The next step will be to chain these responsibilities of commands, in case there a processing chain required. For which i would choose.</p>\n\n<p><a href="http://www.blackwasp.co.uk/ChainOfResponsibility.aspx" rel="noreferrer">http://www.blackwasp.co.uk/ChainOfResponsibility.aspx</a></p>\n\n<p>I guess the combination of these two are best to organize the code for command line processing or any menu driven approach.</p>\n'}, {'answer_id': 38641650, 'author': 'Meadock', 'author_id': 1013794, 'author_profile': 'https://Stackoverflow.com/users/1013794', 'pm_score': 1, 'selected': False, 'text': '<p>How about the interpreter pattern?\n<a href="http://www.dofactory.com/net/interpreter-design-pattern" rel="nofollow">http://www.dofactory.com/net/interpreter-design-pattern</a></p>\n'}]
['https://Stackoverflow.com/questions/54421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/577/']