I am interested in the question of how program arguments work on different operating systems (Debian / Linux, FreeBSD, Solaris, etc).

For example, take the standard ls program, and run it with the arguments -a -l. We get a conclusion. However, running ls -la , ls -al , ls -l -a - we get the same conclusion. I would like to know - is this behavior somehow controlled by the developers? For example, I will write a program that will work with the following arguments: -R -t -dT , how can the user start the program, as shown in the example ls ? Is this "regulated" by the author of the tool?

    1 answer 1

    Is this "regulated" by the author of the tool?

    Yes and no. The programmer must consciously provide this in his program, but for this there is a standard library function - getopt() and the built-in shell command getopts . Both are standardized by POSIX. Interfaces to getopt are available in almost all languages.

    For example, I will write a program that will work with the following arguments: -R -t -dT,

    Assuming that it is -d and -T are two different keys, in C, a typical processing example would look something like this:

     #include <stdbool.h> #include <stdlib.h> #include <unistd.h> void usage(const char* name) { printf(stderr, "Usage: %s" -[RtdT] [-f <file>], name); } int main (int argc, char **argv){ bool recursive=0; bool show_directory=0 bool super_time=0; char *file; int c; while ((c = getopt (argc, argv, "RtdTf:")) != -1) { switch (c) { case 'R': recursive = 1; break; case 't': process_time = 1; break; case 'd': show_directorye = 1; break; case 'T': process_time = 0; break; case 'f': file = optarg break; case 'h': usage(argv[0]); return EXIT_SUCCESS; case '?': return EXIT_FAILURE; default: assert(0); } } // do stuff return EXIT_SUCCESS; } 

    glibc also provides the function getopt_long () , which supports the parsing of long arguments like - --some-option and - --some-option-with-arg=val , but this is only a GNU extension.

    For example, take the standard ls program, and run it with the arguments -a -l. We get a conclusion.

    This behavior of most utilities, by the way, is also standardized by POSIX.

    • one
      getopt () and, most importantly, utility syntax guideline - aleksandr barakin
    • @alexanderbarakin, yes, thanks, I accidentally deleted a paragraph with a link ... - Fat-Zer February