How to set parameter zero ($0) while executing a script?
Other than what Stephane has already mentioned, the only other ways I can think to do it involve invoking an sh
process - which means your function might as well be a script. But if you're still interested:
fn() { sh -c "$(cat)" arg0 "$@" ; } <<\FNDEF
echo "My argv0 is $0 and my positionals are..."
printf %s\\n "$@"
#END
FNDEF
fn arg1 arg2 arg3
###OUTPUT###
My argv0 is arg0 and my positionals are...
arg1
arg2
arg3
It's not terribly useful, though, I don't think.
In Bash greater than or equal to 5 you can change $0
like this:
$ cat bar.sh
#!/bin/bash
echo $0
BASH_ARGV0=lol
echo $0
$ ./bar.sh
./bar.sh
lol
ZSH even supports assigning directly to 0
:
$ cat foo.zsh
#!/bin/zsh
echo $0
0=lol
echo $0
$ ./foo.zsh
./foo.zsh
lol