Is passing a different $0 to a child bash script possible?

You cannot "fool" the child script, but you can call it via a different name by creating a symlink to the called script and calling the symlink. This will, I believe achieve the objective you are looking for.

Example:

$ cat ./bin/script.sh
echo $0

$ ./bin/script.sh
./bin/script.sh
$ ln -s bin/script.sh foo.sh
$ ./foo.sh
./foo.sh

Maybe this will do:

bash -c '. /path/to/unmodifiable' /fake/path args ...

Obviously, /path/to/unmodifiable should be a shell script; this silly trick won't work with other kind of executables. This also won't work with zsh (but will work with other shells like dash, ksh, etc).

If you have to source instead of call the unmodifiable script, you can use the same trick from a wrapper calling your outer script, or have it re-call itself:

$ cat unmodifiable
#! /bin/sh
printf '{%s} ' "$0" "$@"
echo

$ cat becoming
#! /bin/sh
[ "$MYSELF" ] || MYSELF=$0 exec sh -c '. "$MYSELF"' "I'm the mountain!" "$@"
. ./unmodifiable

$ chmod 755 becoming
$ ./becoming 1 2 3
{I'm the mountain!} {1} {2} {3}

Tags:

Bash

Arguments