bash - Linux 命令在 shell 命令行中表现异常

标签 bash shell command-line

请看下面的命令:

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/

相关文章:

linux - 如何使用 bash 脚本更改 iptable 条目?

java - Java中执行/usr/bin/env bash -c "command"

linux - Bash:从 ./将所有目录的内容移动到各自的 ../

bash - 无法使用 curl : argument too long 将大文件发送到 elasticsearch

linux - 在脚本中使用 fish shell 函数

python - 检查文件中的一组字符串是否在另一个文件中或不使用 python 或 bash

android - 如何为 Android 构建命令行应用程序?

ruby-on-rails - 设置 Rails 时出现问题,sqlite 3 无法安装

bash - 为什么$需要加转义符?在评估中?

swift - 从 Xcode 调试应用程序时,从终端命令获取相同的 PATH 环境变量?