4

what is the difference bw:

  1. exec script.sh and
  2. bash script.sh

assuming script.sh has all the appropriate reading/executing permissions set?

1 Answers1

7

exec script.sh replaces the current shell with the one defined in the shebang line of script.sh, and uses that interpreter to run the rest of the file. This could be anything from /bin/sh to /usr/bin/python, no matter what the filename extension is. To do this, script.sh has to be executable. One of the side effects of this is that when script.sh is done the shell also exits. If it is an interactive terminal, the terminal will exit as well.

bash script.sh uses a new bash shell to interpret script.sh, independent of the shebang line. That is, if there is a shebang line it is ignored. script.sh does not have to be executable to run it this way.

l0b0
  • 51,350
  • 1
    exec script.sh would also look for it through PATH, I think. bash script.sh won't – ilkkachu Apr 19 '21 at 22:37
  • "the terminal will exit as well" -- depending on how the terminal is configured. – glenn jackman Apr 20 '21 at 00:37
  • @glennjackman Every single statement about Bash scripting needs a caveat of "in the vast majority of circumstances". :) The last time I encountered a terminal which didn't exit when the child shell exited was about a decade ago. – l0b0 Apr 20 '21 at 01:01
  • 1
    @ilkkachu Bash is the only shell I can test with that performs a PATH search if script.sh is not found in the current directory (as documented). I was actually surprised to see that other shells don't... – fra-san Apr 20 '21 at 10:04
  • 2
    @fra-san, it does? Hngh. Well, Ksh does too, so it's probably inherited from there. Anyway, the point was mostly that as far as I can test, exec script.sh looks at PATH first, and only there, while bash script.sh looks at the current directory first, and then at PATH. – ilkkachu Apr 20 '21 at 10:29