如何更改shell / bash脚本中的argv [0]值?

时间:2014-06-30 09:58:41

标签: bash shell sh dash-shell

set命令可用于更改位置参数$ 1 $ 2 ...

的值

但是,有没有办法改变$ 0?

3 个答案:

答案 0 :(得分:1)

这是另一种方法。它是通过直接命令执行来实现的,这比命令(点命令)要好一些。但是,此方法仅适用于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

答案 1 :(得分:0)

#! /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

答案 2 :(得分:0)

在Bash大于或等于5的情况下,您可以像这样更改$0

$ cat bar.sh
#!/bin/bash
echo $0
BASH_ARGV0=lol
echo $0
$ ./bar.sh 
./bar.sh
lol

ZSH甚至支持直接分配给0

$ cat foo.zsh
#!/bin/zsh
echo $0
0=lol
echo $0
$ ./foo.zsh 
./foo.zsh
lol