使用方法: 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
参考资料
- https://www.gnu.org/software/bash/manual/html_node/Invoking-Bash.html
- https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Special-Parameters
- https://unix.stackexchange.com/questions/280454/what-is-the-meaning-of-0-in-the-bash-shell