set
命令可用于更改位置参数$1 $2 ...的值。但是,是否有任何方法可以更改$0?(注:$0是指shell脚本文件名或者shell程序名称)
set
命令可用于更改位置参数$1 $2 ...的值。但是,是否有任何方法可以更改$0?$0
:$ cat bar.sh
#!/bin/bash
echo $0
BASH_ARGV0=lol
echo $0
$ ./bar.sh
./bar.sh
lol
0
:$ cat foo.zsh
#!/bin/zsh
echo $0
0=lol
echo $0
$ ./foo.zsh
./foo.zsh
lol
这里介绍另一种方法。它是通过直接执行命令来实现的,比使用“点”命令(sourcing)要好一些。但是,这种方法只适用于shell解释器,而不是bash,因为sh支持同时传递-s -c选项:
#! /bin/sh
# try executing this script with several arguments to see the effect
test ".$INNERCALL" = .YES || {
export INNERCALL=YES
cat "$0" | /bin/sh -s -c : argv0new "$@"
exit $?
}
printf "argv[0]=$0\n"
i=1 ; for arg in "$@" ; do printf "argv[$i]=$arg\n" ; i=`expr $i + 1` ; done
如果运行 ./the_example.sh 1 2 3
,两个示例的预期输出应为:
argv[0]=argv0new
argv[1]=1
argv[2]=2
argv[3]=3
/bin/sh
解释器。 - bgoodr#! /bin/sh
# try executing this script with several arguments to see the effect
test ".$INNERCALL" = .YES || {
export INNERCALL=YES
# this method works both for shell and bash interpreters
sh -c ". '$0'" argv0new "$@"
exit $?
}
printf "argv[0]=$0\n"
i=1 ; for arg in "$@" ; do printf "argv[$i]=$arg\n" ; i=`expr $i + 1` ; done
INNERCALL=YES exec sh -c ". '$0'" argv0new "$@"
使内部调用代码更加简洁。我有点怀疑. '$0'
命令存在被破坏的可能性,但我可以先不考虑那些需要非常不寻常的设置技巧。但如果没有解释,我就不能认为这是一个好的答案。 - Jonathan Leffler