请看下面的命令:
administrator@ubuntu:~/usp$ cat file
c
b
a
administrator@ubuntu:~/usp$ x="cat file | sort"
administrator@ubuntu:~/usp$ $x
c
b
a
cat: |: 没有那个文件或目录
cat: sort: 没有那个文件或目录
我的问题是为什么 $x 的输出不是:
a
b
c
双引号改变命令 cat file | 的行为排序
?
最佳答案
发生的事情是 $x
作为单个命令执行。 shell 不会“重新解析”$x
的内容,因此它不会特别设置重定向和生成 sort
。
cat
得到三个参数:file
、|
和sort
。该目录中没有名为 |
或 sort
的文件,因此 cat
无法打开它们。 (我猜错误是什么意思1。)
你可以通过运行得到你期望的结果:
eval "$x"
如果可以的话,我会避免使用 eval
,它 can be dangerous .
1在您的命令前加上 LC_ALL=
前缀,以便在国际站点寻求帮助之前获得英文错误消息。
例如LC_ALL= $x
。
关于bash - Linux 命令在 shell 命令行中表现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16385835/