sh 文件中的 Cat 不回显空行

Cat in sh file doesn't echo empty lines

文件 myfile.sh 如下所示:

echo "hello"








我 运行 的文件如下所示:

a=$(cat myfile.sh)
echo $a

当我运行文件时,我只得到输出:

echo "hello"

而不是实际的文件内容。这是怎么回事?

http://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html

a=$(cat myfile.sh) 你的变量被赋值

the standard output of the command, with any trailing newlines deleted

这就是你多余的行所在的地方。

来自我系统上 dash (/bin/sh) 的手册页,

The shell expands the command substitution by executing command in a subshell environment and replacing the command substitution with the standard output of the command, removing sequences of one or more ⟨newline⟩s at the end of the substitution. (Embedded ⟨newline⟩s before the end of the output are not removed; however, during field splitting, they may be translated into ⟨space⟩s, depending on the value of IFS and quoting that is in effect.)

(强调我的。)

您可以使用以下内容:

#!/bin/sh

LF='
'

a=
while read -r line; do
   a="$a$line$LF"
done

printf -- '--\n%s--' "$a"

测试:

$ printf 'a   b   c\nd\n\n\ne\n\n\n' | ./a.sh
--
a   b   c
d


e


--