Bash – Difference between sh -x and ./ for script execution

bashscriptingshell-script

So I have a simple shell script. What is the difference between the two commands in execution? Is there a preferred way?

$sh -x foobar.sh

OR

$ ./foobar.sh

I found the script executed slower when used with the second command.

Best Answer

The ./foobar.sh file is started by running it with whatever follows the #! in the first line. If this line reads #!/bin/sh -x then it would be identical to the sh -x foobar.sh case (assuming sh is resolved to /bin/sh from the PATH). Maybe it is not started by sh but bash?

The -x flag prints debug info, i.e. every command before it is executed.