微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐