Shell – Distance of a command from a shebang

shebangshell-script

A shebang (#!/bin/sh) is placed on the first line of a bash script, and it's usually followed on the second line by a comment describing what action the script performs. What if, for no particular reason, you decided to place the first command far beneath the shebang and the comment by, say, 10000 lines. Would that slow the execution of the script?

Best Answer

To find out, I created two shell files. Each starts with a shebang line and ends with the sole command date. long.sh has 10,000 comment lines while short.sh has none. Here are the results:

$ time short.sh 
Wed Nov 12 18:06:02 PST 2014

real    0m0.007s
user    0m0.000s
sys     0m0.004s

$ time long.sh
Wed Nov 12 18:06:05 PST 2014

real    0m0.013s
user    0m0.004s
sys     0m0.004s

The difference is non-zero but not enough for you to notice.

Let's get more extreme. I created very_long.sh with 1 million comment lines:

$ time very_long.sh
Wed Nov 12 18:14:45 PST 2014

real    0m1.019s
user    0m0.928s
sys     0m0.088s

This has a noticeable delay.

Conclusion

10,000 comment lines has a small effect. A million comment lines cause a significant delay.

How to create long.sh and very_long.sh

To create the script long.sh, I used the following awk command:

echo "date" | awk 'BEGIN{print "#!/bin/bash"} {for (i=1;i<=10000;i++) print "#",i} 1' >long.sh

To create very_long.sh, I only needed to modify the above code slightly:

echo "date" | awk 'BEGIN{print "#!/bin/bash"} {for (i=1;i<=1000000;i++) print "#",i} 1' >very_long.sh
Related Question