bash - cat `bash` 命令的意外输出

标签 bash shell unix operating-system cat

有人可以解释一下吗?我运行了如下所示的命令

$ cat `bash`

$ ls

$ ctrl+D

它在终端上给了我一些意想不到的输出。

注意:bash 在反引号中。

最佳答案

好问题! “意外输出”是 cat 打印 ls 在 cwd 中找到的所有文件。详细解释如下:

在你的第一行:

$ cat `bash`

bash 部分实际上从您的原始 shell 中生成了一个新的 shell,因为 bash 被反引号括起来(反引号意味着在此上下文中运行封闭的程序)

然后当你这样做时:

$ ls

这实际上是在新生成的 bash shell 中完成的。它列出了新生成的 bash shell 所在的目录(应该与原来的相同)。反过来,这实际上将第一步中的 cat 命令更改为

$ cat file_1 file_2 ... file_x

(基本上是 ls 返回的该目录中的所有文件。但是,您还不会看到这些结果,因为输出正在等待打印到原始 shell 的标准输出:cat is waiting to evaluate the stdout of你的新 bash shell。)

最后,当您这样做时:

$ ctrl+D

它退出您从原始 shell 生成的新 bash shell,然后 cat 将新 shell 中打印到 stdout 的所有内容(来自 ls 的搜索结果)输出到您的旧 shell。

你可以通过以下方式验证我刚才说的话:

$ cd ~/
$ mkdir temp_test_dir
$ cd temp_test_dir
$ echo "some text for file1" > file1
$ echo "other text for file2" > file2

现在运行你的问题:

$ cat `bash`
$ ls
$ ctrl+D

这是你应该看到的:

some text for file1
other text for file2

按某种顺序,这只是 cat 输出 ls 找到的所有文件。

关于bash - cat `bash` 命令的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12948611/

相关文章:

linux - 运行命令,然后通过SQLCMD添加结果

bash+xmlstarlet : How can one index into a list, 还是填充数组?

bash - Ctrl-C 如何终止子进程?

bash - 在期望脚本中发送 INSERT 和 F12

sockets - Unix 中的 TCP 套接字 - 通知服务器我已完成发送

string - bash 从文件中的每个字符串中读取一个字符

python - 用 python 改进 bash 脚本

shell - 对制表符分隔文件中的所有 "cells"执行算术运算

bash - 命令替换 : backticks or dollar sign/paren enclosed?

Bash命令行和输入限制