当我运行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
造成这种行为的原因是什么?
最佳答案
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/