Can we use two shebang statements in a single shell script?

Hi,

As per my understanding, we can use two shebang statements in a single shell script. Please see below snippet-

#!/bin/bash
.......## some code A
#!/bin/csh
.......## some code B
exit 0;

Here, code A will be executed using bash shell and code B will be executed with c shell.

Please let me know, in case, if I'm wrong.

Also, please tell me how to know the current running shell in shell script.

Regards,
Tarun0

no you cannot use it.

The shebang works only when

  1. it is on the first line
  2. it starts in column one

If you need to run some code in another shell -

#!/bin/bash
....
...
/bin/ksh -c ' your command goes here'  # can't type - removed shebang

This executes one line using ksh. Otherwise you have to invoke the other shell in a separate script.

#!/bin/bash
/path/to/script.csh
/path/to/anotherscript.ksh

I added .csh and .ksh extensions to show what shell they use, the .ksh extension, for example, has no effect on actual shell choice in the script.

Without the shebang then, no?

/bin/ksh -c ' your command goes here'

scrutinizer - thanks, I fixed it. My bad.

Thanks guys !

Still there is one doubt!

what happens when we source a script having shebang statement of C shell(for instance) into the script having shebang statement of K shell?

In this case, does the sourced script(with C shell shebang) execute in C shell(child process) and return the output in running script with K shell(parent shell) shebang.

See below snippet-

running script is -
#!/bin/ksh
...some code...
source <sourced script name>
exit 0;

where the sourced script is -
#!/bin/csh
...some code;
exit 0;

You cannot source the csh script inside the ksh script, you need to execute it so that it runs in a separate (c-)shell

This question implies you don't know why the shebang works. Shells ignore it -- it's a comment as far as they're concerned because it starts with # It has absolutely no effect on sourced scripts once, let alone twice.

The OS handles them itself, on exec(). It does it as part of its checking of what kind of executable file a program is. It checks the first two bytes of the file. If it finds #!, it assumes its a shell script and runs the appropriate interpreter. If it finds an ELF header, it loads the executable into memory and runs it that way. If it's a raw a.out executable it loads it in a different manner then executes it. If it finds neither, it assumes it should use the /bin/sh interpreter.

So, the hash-bang only ever does anything -- at all -- ever -- when you're executing a script, not sourcing it, and even then, it works only once, at the very beginning of the file. That's when the OS reads it and picks the interpreter. After that the shell takes over, and it cares not at all about lines beginning with #.

2 Likes

Thanks a lot you all guys for such a useful information :slight_smile:

To Know currently running shell use following command,

echo $SHELL