如何将文件读入 bash 中的变量

How can I read a file into a variable in bash

我想将文件的内容存储在 bash shell 变量中。这很好用:

$ cat hello
Hello, world!
$ F=hello
$ Q=$(cat $F)
$ echo $Q
Hello, world!

但是,如果文件包含星号,则星号将替换为当前目录中所有文件的列表。

如何引用文件名来保护星号?或者以其他方式将文件加载到 shell 变量中?

我知道 this question,但它不适用于包含星号的文件。

Q 包含星号。它是 $Qunquoted 扩展,用文件列表替换 *

$ Q="*"
$ echo $Q
<list of files>
$ echo "$Q"
*

赋值的右侧不受路径名扩展的影响,因此 Q=* 也可以工作,用于从文件读取的命令替换也不受影响。 Q=$(cat hello) 工作正常:您只需要引用 Q.

的扩展