linux - 为什么 echo `cat file` 会丢失所有格式?

标签 linux bash cat

当我运行cat时我直接得到了与文件中完全相同的格式化文本。

$ cat hostnamectl.output
   Static hostname: linuxtb3
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 76073c1aa8cf48ed900c39d1992fbb73
           Boot ID: 24db61d58fd5491bbf82a4bb743e5b72
    Virtualization: kvm
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 3.10.0-957.21.3.el7.x86_64
      Architecture: x86-64

当我在 echo 之后运行它时所有格式都会丢失。

$ echo `cat hostnamectl.output`
Static hostname: linuxtb3 Icon name: computer-vm Chassis: vm Machine ID: 76073c1aa8cf48ed900c39d1992fbb73 Boot ID: 24db61d58fd5491bbf82a4bb743e5b72 Virtualization: kvm Operating System: CentOS Linux 7 (Core) CPE OS Name: cpe:/o:centos:centos:7 Kernel: Linux 3.10.0-957.21.3.el7.x86_64 Architecture: x86-64

造成这种行为的原因是什么?

最佳答案

来自Greg's Bash Guide :

2. Quoting

Word Splitting is the demon inside Bash that is out to get unsuspecting newcomers or even veterans who let down their guard. ...The best way to protect yourself from this beast is to quote all your strings. Quotes keep your strings in one piece and prevent Word Splitting from tearing them open.

...

Here's another example to show you just how badly you can break things if you neglect to quote when necessary:

$ echo "$(ls -al)"
total 8
drwxr-xr-x   4 lhunath users 1 2007-06-28 13:13 "."/
drwxr-xr-x 102 lhunath users 9 2007-06-28 13:13 ".."/
-rw-r--r--   1 lhunath users 0 2007-06-28 13:13 "a"
-rw-r--r--   1 lhunath users 0 2007-06-28 13:13 "b"
-rw-r--r--   1 lhunath users 0 2007-06-28 13:13 "c"
drwxr-xr-x   2 lhunath users 1 2007-06-28 13:13 "d"/
drwxr-xr-x   2 lhunath users 1 2007-06-28 13:13 "e"/
$ echo $(ls -al)
total 8 drwxr-xr-x 4 lhunath users 1 2007-06-28 13:13 "."/ drwxr-xr-x 102 lhunath users 9 2007-06-28 13:13 ".."/ -rw-r--r-- 1 lhunath users 0 2007-06-28 13:13 "a" -rw-r--r-- 1 lhunath users 0 2007-06-28 13:13 "b" -rw-r--r-- 1 lhunath users 0 2007-06-28 13:13 "c" drwxr-xr-x 2 lhunath users 1 2007-06-28 13:13 "d"/ drwxr-xr-x 2 lhunath users 1 2007-06-28 13:13 "e"/

就像在 ls -al 示例中一样,双引号将解决您的问题:

$ echo "`cat hostnamectl.output`"

然而,用反引号捕获命令的输出然后立即回显捕获的输出是一种反模式。您应该直接调用该命令并跳过额外的步骤:

$ cat hostnamectl.output

关于linux - 为什么 echo `cat file` 会丢失所有格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57202458/

相关文章:

linux - 使用 bash 检查 node.js 应用程序是否已正确启动

amazon-web-services - gitlab CI 因 cloudformation 部署参数覆盖而失败

c - 没有正确读取标准输入

linux - 为什么我很少而不是总是得到 "cat: write error: Broken pipe"

bash - 当我 cat 文件时获取变量替换

linux - pypy3 安装加密失败

linux - sudo -s 和 sudo 有什么区别

linux - 诺基亚 S40 手机的时钟与 PC 上的当前日期时间同步?

mysql - sed 错误,而下划线是搜索文本的一部分

将静态库转换为共享库?