How to change argv[0] value in shell / bash script?

前端 未结 3 857
无人及你
无人及你 2021-01-15 05:11

The set command can be used to change values of the positional arguments $1 $2 ...

But, is there any way to change $0 ?

相关标签:
3条回答
  • 2021-01-15 05:26

    Here is another method. It is implemented through direct commands execution which is somewhat better than sourcing (the dot command). But, this method works only for shell interpreter, not bash, since sh supports -s -c options passed together:

    #! /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 expected output of the both examples in case ./the_example.sh 1 2 3 should be:

    argv[0]=argv0new
    argv[1]=1
    argv[2]=2
    argv[3]=3
    
    0 讨论(0)
  • 2021-01-15 05:31
    #! /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
    
    0 讨论(0)
  • 2021-01-15 05:40

    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
    
    0 讨论(0)
提交回复
热议问题