Loading

## sh -c 执行时$0的含义

使用方法: sh -c cmd_string [others]

# 如果others为空,则`$0`表示使用的shell解释器:
bandit33@bandit:~$ sh -c 'echo $0'
sh
bandit33@bandit:~$ bash -c 'echo $0'
bash
# 如果others不为空,则`$0`表示第一个其他参数
bandit33@bandit:~$ bash -c 'echo $0' hello world
hello

单引号与双引号

# 使用双引号将只能调用当前shell
bandit33@bandit:~$ bash
bandit33@bandit:~$ sh -c "echo $0"
bash
bandit33@bandit:~$ sh -c 'echo $0'
sh

# 使用双引号无法过滤掉$0中的特殊字符
# 比如,登录进去的shell的是login shell,`echo $0`会在开头多打印一个短线`-`
bandit33@bandit:~$ echo $0
-bash

# 此时使用双引号就会和单引号表现有极大不同
bandit33@bandit:~$ sh -c "echo $0"
-bash
bandit33@bandit:~$ sh -c "ls $0" # -bash被错误解释成ls -bash
total 24K
4.0K .  4.0K ..  4.0K .bash_logout  4.0K .bashrc  4.0K .profile  4.0K README.txt

参考资料

  1. https://www.gnu.org/software/bash/manual/html_node/Invoking-Bash.html
  2. https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Special-Parameters
  3. https://unix.stackexchange.com/questions/280454/what-is-the-meaning-of-0-in-the-bash-shell
posted @ 2021-10-02 14:39  Sherlock-Tang  阅读(526)  评论(0编辑  收藏  举报