1

What is the difference between running a script file like this:

sh myfile.sh

Or this:

./myfile.sh

I thought they are the same thing, but noticed sometimes they are not, as seen below example:

root@kali:~/Documents# sh sweep-ips.sh
ips range:
ping: 10.11.1.{0..24}: Name or service not known

root@kali:~/Documents# ./sweep-ips.sh 
ips range:
64 bytes from 10.11.1.5: icmp_seq=1 ttl=128 time=242 ms
64 bytes from 10.11.1.8: icmp_seq=1 ttl=64 time=249 ms
64 bytes from 10.11.1.22: icmp_seq=1 ttl=255 time=249 ms
64 bytes from 10.11.1.24: icmp_seq=1 ttl=64 time=241 ms

script:

#!/bin/bash
echo "ips range"

for ip in 10.11.1.{0..24}
 do
   ping -c 1 ${ip} | grep "time=" 
 done
peterh
  • 9,488
  • 16
  • 59
  • 88
Spring
  • 143
  • 6
  • 2
    In short `$shell ./script.sh` run it through `$shell`, but `./script.sh` runs it through whatever the `#!` line in the script says. In this case I suppose you have the shebang (quite correctly!) set to Bash or such but that your `sh` is just POSIX sh (like `dash` on Debian and Ubuntu). – ilkkachu Dec 05 '17 at 18:47
  • @ilkkachu thnx, but confused. Then should I always use the syntax ./myfile.sh ? and not sh filename? Or both has their uses? – Spring Dec 05 '17 at 18:58
  • 4
    @Spring, you should usually use `./mycmd`, since in that case you don't need to think what the expected interpreter is. (Instead of a shell script, it could be Perl, or `awk`, or `expect`, or...) The only reason to use `sh ./mycmd` or `bash ./mycmd` would be to test how the script runs with _that particular shell_, perhaps to test for portability (or lack of it). – ilkkachu Dec 05 '17 at 19:01
  • @ilkkachu tnx! One last question, if I run the same scripts on mac os terminal or kali linux, I see sometimes kali shell complains about my grep, cut syntax. isn't the bash used supposed to be same? I can create a different question if you wish – Spring Dec 05 '17 at 19:07

1 Answers1

1

./script.sh is executing a script in samy way we execute a binary file. The interpreter is picked from #! in case it's a script and not a binary.

bash script.sh invoke bash as a interpreter to execute the script.

Both looks almost same, buth there are differences.

One major difference is script.sh must be executable for ./script.sh to work. That's a file with 644 permission can't be executed in this way. On the other hand for bash script.sh predefined interpreter /bin/bash is already executable. So a file with 644 permission works with this method.

Abhik Bose
  • 2,090
  • 2
  • 15
  • 30