LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   different way of executing shell script (https://www.linuxquestions.org/questions/linux-newbie-8/different-way-of-executing-shell-script-4175416188/)

vaibhavs17 07-11-2012 01:49 PM

different way of executing shell script
 
what is the difference between including poundbang in the shell script or not using poundbang in the script?

count.ksh
#!/bin/bash
echo "hello"

> ./count.ksh

other way

count.sh

echo "hello"


>sh count.sh

Kustom42 07-11-2012 02:14 PM

Ok, first lets clarify that its not called a poundbang but a "shebang".

This declares the location of the interpreter for the language. Yes a simple echo can be run without one as if there is not one it will assume that /bin/sh should be used which is a sym link to whatever shell you are currently using(ksh, bash, etc..).


The importance of this becomes clear as you try to create more indepth scripts in other languages. Here's how to see this in action:

Put the following into a file and make it executable.
Code:

print "I will now count my chickens:"

print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4

print "Now I will count the eggs:"

print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6

print "Is it true that 3 + 2 < 5 - 7?"

print 3 + 2 < 5 - 7

print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7

print "Oh, that's why it's False."

print "How about some more."

print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2

Now try and run the script, it will error as bash or ksh cannot interpret these commands. Now add a shebang to specify python as your interpeter:

Code:

#!/usr/bin/python
And run the script and it will work.



NOTE: The above code was an excerpt take from http://learnpythonthehardway.org/book/ex3.html for use as a quick educational example.

Kustom42 07-11-2012 02:15 PM

http://wiki.linuxquestions.org/wiki/Shebang

chrism01 07-11-2012 06:11 PM

Indeed your 1st example calls it count.ksh, but it will run using bash because bash was specified; not a good idea...
If no shell is specified ie no shebang line, it'll use the current default shell, which may not be what you wanted.
There are important differences between the various shell parsers.
For prod code ALWAYS specify the one you want as the first line.


All times are GMT -5. The time now is 10:54 AM.