我是 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/