Fun with polymorphic shell scripts
Imagine you have two shell scripts in the same directory.
test1.sh:
#!/bin/bash echo "I am test1" cp test2.sh test1.sh
test2.sh:
#!/bin/bash echo "I am test2" cp test2.sh test1.sh echo "This should not get printed"
Now run test1.sh. What do you expect the output to be?
I’d imagine that bash would run a copy of test1.sh in memory, and as a result of that execution, test1.sh would be replaced with test2.sh at the end of execution. But I would be wrong. This is the output I get after running test1.sh:
$ ./test1.sh I am test1 This should not get printed
What the?
I actually made a demo in one liner form while you were writing this:
That is completely counterintuitive. I had assumed it runs a copy in memory (and it behaves like it does this to a point):