Reputation: 295
This is the content of my script
#!/bin/bash
# test.sh
# Note: Set permissions on this script to 555 or 755,
# then call it with ./test.sh or sh ./test.sh.
echo
echo "This line appears ONCE in the script, yet it keeps echoing."
echo "The PID of this instance of the script is still $$."
# Demonstrates that a subshell is not forked off.
echo "==================== Hit Ctl-C to exit ===================="
sleep 1
exec $0 # Spawns another instance of this same script
#+ that replaces the previous one.
echo "This line will never echo!" # Why not?
exit 99 # Will not exit here!
# Exit code will not be 99!
And this is the output when I run the script using /bin/bash
[user@localhost ~]$ /bin/bash test.sh
This line appears ONCE in the script, yet it keeps echoing.
The PID of this instance of the script is still 4872.
==================== Hit Ctl-C to exit ====================
test.sh: line 11: exec: test.sh: not found
This is the output when I run the script using /bin/sh
[user@localhost ~]$ /bin/sh ./test.sh
This line appears ONCE in the script, yet it keeps echoing.
The PID of this instance of the script is still 4934.
==================== Hit Ctl-C to exit ====================
This line appears ONCE in the script, yet it keeps echoing.
The PID of this instance of the script is still 4934.
==================== Hit Ctl-C to exit ====================
I had to use Ctl-C to stop this.
Why does the same script behave differently based on different mode of execution. FYI: I had to use Ctl-C which I executed the script like this: ./test.sh
Upvotes: 0
Views: 1182
Reputation: 753455
You get the error test.sh: not found
because you don't have the current directory in your PATH.
When you run it with ./test.sh
, the pathname is relative and PATH is not consulted, so the command is found.
Note that /bin/bash ./test.sh
would iterate, and /bin/sh test.sh
would fail; it is not an issue of the difference between /bin/bash
and /bin/sh
.
Upvotes: 1
Reputation: 72527
The first time you run this script using /bin/bash test.sh
. The second time, you run it with /bin/sh ./test.sh
. Note the difference: test.sh
vs ./test.sh
.
For whatever reason, the script is unable to spawn a second process running the script, because it's unable to find test.sh
. (I'm not sure why this is. I'd guess a PATH
issue, perhaps?) See the below error message:
[user@localhost ~]$ /bin/bash test.sh
This line appears ONCE in the script, yet it keeps echoing.
The PID of this instance of the script is still 4872.
==================== Hit Ctl-C to exit ====================
test.sh: line 11: exec: test.sh: not found
The script can't execute test.sh
because it doesn't know where test.sh
is; ./test.sh
is a full path to the script, which is findable.
The second time you run it, the child processes spawn happily, because ./test.sh
is found.
Try running: /bin/bash ./test.sh
and /bin/sh ./test.sh
and see if there's any difference in the output (shouldn't be).
Upvotes: 1