How programs get run
How programs get run
Posted Jan 29, 2015 6:16 UTC (Thu) by wahern (subscriber, #37304)Parent article: How programs get run
After checking those first two bytes, this code parses the rest of the script-invocation line, splitting it into an interpreter name (everything after #! up to the first white space) and possible arguments (everything else up to the end of the line, stripping external white space).Linux passes the remainder of the line as a _single_ argument. You show this in your example where "-a -b -c" are all located in argv[1]. But you say
... a third extra argument is also inserted, holding all of the extra options:
Those aren't extra options--the plural is misleading. The distinction matters because neither getopt nor getopt_long will parse "-a -b -c" as three separate options. Rather, it'll be parsed as optc='a' and optarg=" -b -c", or it will parse as optc='a', optc=' ', optc='-', optc='b', etc. Most likely it'll just fail because your option specification won't match the parse. If a, b, and c are all single options without arguments, then you could put "-abc" on the shebang line. But you can't space them out, and you can't use an option that takes an argument unless the argument is the path of the script, as with the -f option for awk. And you can't mix non-argument with argument options unless the sole argument-taking option comes last. For example, "-abcf".
OS X, by contrast, will field-split the trailing shebang line in the kernel so that the script "#!./show_info -a -b -c" will print out
argv[0] = './show_info' argv[1] = '-a' argv[2] = '-b' argv[3] = '-c'
Solaris is quirky. It will field-split, but only includes the first field. So "#!./show_info -a -b -c" will print out
argv[0] = './show_info' argv[1] = '-a'
FWIW, OpenBSD 5.5, NetBSD 6.1, and FreeBSD 9.0 all behave like Linux. Which was surprising because I could have sworn that either FreeBSD or NetBSD (or both) would field-split the remainder of the shebang line.
