The Shebang!

Hi,

I always thought that #!/usr/bin/ksh means that the script would be executed in korn shell i.e. when we'll execute the script with this line as the very first line then the shell spawns a korn shell (in this case as we are using #!/usr/bin/ksh ) and the script gets executed.

But I am not sure if my understanding is correct because I tried to execute a script with #!/usr/bin/ksh
as below:

sh a_korn_shell_script.ksh

from a GUI tool. The script failed! with the following error

 
a_korn_shell_script.ksh: line 14: syntax error in conditional expression: unexpected token `('
a_korn_shell_script.ksh: line 14: syntax error near `+(['
a_korn_shell_script.ksh: line 14: `if [[ $var = +([0-9]) ]]'

The snippet of the code which was giving problem

 
if [[ $var = +([0-9]) ]];then
echo "number"
else
echo "not number"
fi

But when I executed it as below:

ksh a_korn_shell_script.ksh (NOTE: This is through GUI tool) OR ./a_korn_shell_script.ksh (NOTE: This is in unix box)

it succeeded.

+ var=0
+ echo number
number

I came accross this link: #!/usr/bin/ksh Command Interpreter in a sh script
which means that even if we use #!/usr/bin/ksh line we should not feed a korn shell script to sh shell??

The default shell is

 
echo $SHELL
/bin/bash

Please execuse me if you think my question is very basic.
-dips

Because you execute your script this way

sh a_korn_shell_script.ksh

your script is actually run under the Bourne shell - not Korn. The first line is treated like a comment since it starts with a "#".

Try running your script without the "sh" and see what happens.

You're launching a_korn_shell_script.ksh with sh shell. In that case, shebang is ignored.

You are asking your script to execute as a bourne script by prefacing it with "sh".

For kicks and giggles, try the following:
Remove the "#!/blah/blah" from the first line of your script. Then try to run the script with the following command:

ksh a_korn_shell_script.ksh

You will see that the line indicating the "intended" shell, is overridden by telling it explicitly which interpreter to use.

I did that and yes the script executed fine with no errors.

If this is a comment then why we need it? Is it just to tell others that a particular script is intended for which shell?
Please be patient with me and explain this :o

-dips

Actually, you can execute a script without sh, ksh, bash, perl, ... in front of the name on the said script.
If so, the shebang is used to determine which program to call to execute the script.
In that case, you have to make your script executable with something like chmod +x /path/to/your_script
Hope it's clear enough. Others members will surely add more comments and explanations.

This may give some clarity: The Whole Story on #! /usr/bin/ksh.

Thanks Franklin52 for the link.
-dips