将参数 #0 更改为 shell 脚本不起作用

问题描述 投票:0回答:1

我正在尝试替换参数

$0
/
argv[0]
。如果我编译这个c代码:

#include <stdio.h>

int main(int argc, char** argv) {
  printf("# %s #\n", argv[0]);
}

然后使用

exec -a fake ./run
运行它,我得到输出

# fake #

然后我尝试使用以下 shell 脚本:

#!/bin/bash
echo "# $0 #"

但是当我跑步时

exec -a fake ./test.sh
我明白了

# /home/user/test.sh #

为什么参数 0 在 shell 脚本案例中的某个位置被重置?

供参考,这是

exec --help

的相关部分
exec: exec [-cl] [-a name] [command [arguments ...]] [redirection ...]
    Replace the shell with the given command.

    Execute COMMAND, replacing this shell with the specified program.
    ARGUMENTS become the arguments to COMMAND.  If COMMAND is not specified,
    any redirections take effect in the current shell.

    Options:
      -a name   pass NAME as the zeroth argument to COMMAND
      -c        execute COMMAND with an empty environment
      -l        place a dash in the zeroth argument to COMMAND
linux bash shell
1个回答
-1
投票

如果您使用 strace 运行:

strace -fe execve bash -c 'exec -a fake ./test.sh' one two
execve("/usr/bin/bash", ["bash", "-c", "exec -a fake ./test.sh", "one", "two"], 0x7ffd9c557aa0 /* 56 vars */) = 0
execve("/home/pmod/Downloads/test.sh", ["fake"], 0x58fc3a91a130 /* 56 vars */) = 0

你会注意到“fake”is作为第0个参数传递,它只是shell用脚本名称覆盖了$0

© www.soinside.com 2019 - 2024. All rights reserved.