Writing linux command line applications and handling arguments
30 October 2013 By Bhavyanshu Parasher
If you have studied c/c++, then you must know that you always define
main() function because you know the first function that takes control of the program in recognized by that particular name only. In linux, we can pass arguments in command line execution. For example, the popular git syntax for making commits and appending messages to the commit is
git commit -m "Your commit message". The additional information you supply in the command line while running the program are called command line arguments. These constitute the program’s argument list. Let us look at another example.
ls -l command is used to list the files. The
-l in this is the argument. Now if you have been coding on windows Turbo C/C++ compiler, then you must have never tried argv & argc parameters in the
main() function. The first parameter argc is an int value that is set to the number of items in the arg list. The argv is an array of character pointers.
Let us look at an example code on how to pass these important parameters to build a basic GNU/Linux command line application in C.
Well i hate to admit but providing arguments can be a bit annoying. For example, if we have a program that accepts two type of options/flags, short (With one hyphen, quick to type,hard to remember) and long (With two hyphens, time consuming to write, easy to remember), the GNU C lib provides a function that makes it easier for the program to understand both type of options. The function is
getopt.h header file. To use this, you need two data structures. First for the character string containing the valid short options represented by a single char. For the long one, you need to create
option array of type struct. It would look somewhat like this
Pretty easy to implement, right? Typically you would wanna loop through this to process all the options the user has specified & then handle each using a switch statement.
Now if the above mentioned function runs into an invalid option, it will return a ? which will stop the program from executing any further. When handling an option that takes an argument, the global var
optarg points to the text of that argument. After getopt_long has finished parsing, the global var
optind contains the index of the first nonoption argument.
Now let us do some coding using getopt_long to process arguments.
You can view the GNU Coding
Standards’ guidelines for command-line options by invoking the following from a shell prompt on most GNU/Linux systems:
% info “(standards)User Interfaces”.
That’s it. Now you can enjoy building some awesome linux command line applications using the GNU C library.
blog comments powered by Disqus