Hi,

I have a simple question about the Linux Shebang '#!'. Well more of a clarification of how Linux handles #!.

My understanding....

When the operating system 'Linux' encounters an executable file with the first characters #! it will extract the absolute path for the executable from this line..i.e.

#! /home/gerard/share/test/gg

Linux will extract the path '/home/gerard/share/test/' and executable 'gg'.

Linux will then replace the potential process with this image and pass as command line arguments - the name of the file that called it and possible addition arguments..

Now the interrupter(mine is gg) will execute, reading the command line arguments and therefore accessing the script file....

Now I know this is a oversimplification but is it generally correct I enclosed a simple version of how I think this works...I never really found a decent explaination/example of this process only vague/general hints.

My script file ggscript.sh

#! /home/gerard/share/test/gg -1 -2 -3 -4

this is the first line

#this is commented out

this is the second 

#this is commented out

this is the third

this is the end

and my interrupter gg.c

#include <stdio.h>
#include <stdlib.h>

#define ARR_SIZE 200

int main(int argc, char**argv)
{
	FILE *fd;
	char ch[ARR_SIZE];
	int i = 0;

	for (i = 0; i < argc; ++i)
	{
		fprintf(stdout, "argv[%d]->%s\n", i, argv[i]);	
	}

	if (!(fd = fopen(argv[argc - 1], "r")))
	{
		fprintf(stdout, "could not open %s\n", argv[argc - 1]);
		exit(EXIT_FAILURE);
	}

	while (fgets(ch, ARR_SIZE, fd))
	{
		if (ch[0] != '#')/*check for lines starting with # - comments*/
			fputs(ch, stdout);
	}

	fclose(fd);
	exit(EXIT_SUCCESS);
}

output from ./ggscript.sh

argv[0]->/home/gerard/share/test/gg
argv[1]->-1 -2 -3 -4
argv[2]->./ggscript.sh

this is the first line


this is the second


this is the third

this is the end

Your understanding is generally correct.
The only problem is that the script filename is not the last argument ( argv[argc - 1] ) but rather the third:

nezachem@Home ~/tmp/dani/shebang $ ./script -z
argv[0]->/home/nezachem/tmp/dani/shebang/gg
argv[1]->-1 -2 -3 -4
argv[2]->./script
argv[3]->-z
could not open -z

Otherwise I would also add that #! is in fact a magic number, which tells exec() to execute a file by means of an interpreter - exactly as you've described.

PS: some unix variants may parse the "-1 -2 -3 -4" fragment into distinct arguments.

Thankyou for the reply nezachem. Sometimes its hard to find an example or website to 'just come out and say what's happening'. Like I said, I was under the impression that this was the process...Thank-you for the clarification...Gerard

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.