51

我对制作 bash 脚本非常陌生,但我的目标是获取一个我拥有的 .txt 文件并将 txt 文件中的单词字符串分配给一个变量。我已经尝试过了(不知道我是否在正确的轨道上)。

#!/bin/bash
FILE="answer.txt"
file1="cat answer.txt"
print $file1

当我运行这个时,我得到

Warning: unknown mime-type for "cat" -- using "application/octet-stream"
Error: no such file "cat"
Error: no "print" mailcap rules found for type "text/plain"

我能做些什么来完成这项工作?

编辑** 当我将其更改为:

#!/bin/bash
    FILE="answer.txt"
    file1=$(cat answer.txt)
    print $file1

我得到了这个:

Warning: unknown mime-type for "This" -- using "application/octet-stream"
Warning: unknown mime-type for "text" -- using "application/octet-stream"
Warning: unknown mime-type for "string" -- using "application/octet-stream"
Warning: unknown mime-type for "should" -- using "application/octet-stream"
Warning: unknown mime-type for "be" -- using "application/octet-stream"
Warning: unknown mime-type for "a" -- using "application/octet-stream"
Warning: unknown mime-type for "varible." -- using "application/octet-stream"
Error: no such file "This"
Error: no such file "text"
Error: no such file "string"
Error: no such file "should"
Error: no such file "be"
Error: no such file "a"
Error: no such file "varible."

当我输入 cat answer.txt 时,它会打印出这个文本字符串应该是一个变量,但是,我仍然无法让 bash 用这个变量来做到这一点。

4

3 回答 3

79

您需要反引号来捕获命令的输出(并且您可能想要echo而不是print):

file1=`cat answer.txt`
echo $file1
于 2013-01-02T04:06:41.467 回答
72

在 bash 中,$(< answer.txt)等价于$(cat answer.txt),但是是内置的,因此更快、更安全。请参阅bash 手册

我怀疑你正在运行这个print

NAME  
    run-mailcap, see, edit, compose, print − execute programs via entries in the mailcap file
于 2013-01-02T07:28:51.483 回答
39

$()构造stdout从命令返回。

file_contents=$(cat answer.txt)
于 2013-01-02T04:07:07.963 回答