linux - 为什么 "/bin/sh ls"不执行ls?

标签 linux bash shell

我是 shell 新手,抱歉,如果我的问题太基础了。我使用的是 Bash shell,下面是我尝试过的触发命令的不同方法:

ls               // of course it works :)

/bin/sh ls       // error,  ")" unexpected

/bin/sh -c ls    // work just like `ls`

那么为什么 /bin/sh ls 不起作用?不是说我使用ls时,ls/bin/目录下的一个可执行对象,所以ls应该与 /bin/sh ls 相同,不是吗?

最佳答案

why /bin/sh ls doesn't work?

来自posix manual sh的一些相关部分:

sh [-abCefhimnuvx] [-o option]... [+abCefhimnuvx] [+o option]... [command_file [argument...]]

sh -c [-abCefhimnuvx] [-o option]... [+abCefhimnuvx] [+o option]... command_string [command_name [argument...]]

sh -s [-abCefhimnuvx] [-o option]... [+abCefhimnuvx] [+o option]... [argument...]

The sh utility is a command language interpreter that shall execute commands read from a command line string, the standard input, or a specified file. The application shall ensure that the commands to be executed are expressed in the language described in Shell Command Language.

-c Read commands from the command_string operand. [...]

-s Read commands from the standard input.

If there are no operands and the -c option is not specified, the -s option shall be assumed.

command_file The pathname of a file containing commands. [....]

:

 /bin/sh ls

case 属于 sh command_file case。那么命令文件应该包含由 shell 解释的 shell 命令。但是 ls 是一个可执行文件,很可能是 ELF 可执行格式 - 与换行符分隔的 shell 命令相差甚远 - 因此 shell 会因解析器错误而退出。

isn't that when I use ls, ls is an executable object in /bin/ directory, so ls should be the same as /bin/sh ls, shouldn't it?

没有。

inconsistency when calling commands in different ways in shell?

没有。通常解释器和编译器是以将文件传递给它们的方式编写的。当您将文件传递给解释器或编译器时,例如当您执行 gcc file.c 时,您希望使用 C 编程语言编写 file.c ,并且它将得到编译成可执行文件。当您编写 python 文件 时 - 那么 file 预计会用 python 编程语言编写。同样,当您编写 sh 文件 时,无论文件是什么,(在现代/POSIX 操作系统上)都应该以包含 POSIX 兼容 shell 命令的 POSIX sh shell 语言编写,而不是本身就是一个 shell 命令。

关于linux - 为什么 "/bin/sh ls"不执行ls?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63901732/

相关文章:

c++ - 我可以向不同的线程发送信号吗

bash - eval 和反引号(反撇号)之间的区别

linux - 如何处理单引号之间双引号中有空格的变量

bash - shell 脚本到 ssh 远程机器并打印 top 命令的输出

linux - 与 echo 一起使用时脚本不会执行 -

c++ - 在 C/C++ 项目中查找 "undefined"引用

在 Linux mint 中从 C 程序创建临时文件

linux - 如何在 openvz 容器中将 zsh 设置为默认 shell?

sql - mysqldump - 选择包含特定字符串的表

python - 有什么方法可以在更改代码时不重新启动而使用 django shell