When I run cat
directly I get nice formatted text exactly as in the file.
$ 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
When I run it after echo
all formatting is lost.
$ 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
What is the reason for such behavior?
2
Answers
When you run:
You actually calling:
Which is essentially the same as:
This how bash handle args, so you get:
BTW, you can use:
where the
cat xxx
part will be passed to echo as a single stringarg1
, so you will get expected outputFrom Greg’s Bash Guide:
Just like in the
ls -al
example, double quotes will fix your problem:It is, however, an anti-pattern to capture a command’s output with backticks and then immediately echo the captured output. You should simply call the command directly and skip the extra steps: