2013-01-02 23 views
12

我是很新的制作的bash脚本,但在这里,我的目标是把一个txt文件我已经和分配字的字符串中的TXT文件到一个变量。我试过这个(如果我在正确的轨道上没有线索)。需要一个文本文件的内容分配给一个变量在bash脚本

#!/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." 

当我进入猫answer.txt它打印出该字符串应该是一个varible就像它应该但是,我仍然无法得到那个与变数的那个bash。

+0

'file_contents = $(猫answer.txt)'? –

+0

@WaleedKhan我尝试这样做,现在明白了上面的错误 – BluGeni

+3

正如我所说的,我的回答你正在使用的打印而不是回声。另外,你可能不需要'FILE =“answer.txt”'你没有在任何地方使用它。 –

回答

17

你需要反引号从一个命令捕获输出(和你可能想echo代替print):

file1=`cat answer.txt` 
echo $file1 
+0

感谢您找到我的初学者错误! – BluGeni

11

$()建设从命令返回stdout

file_contents=$(cat answer.txt) 
+1

+1;更具体地说,它被称为命令替换:http://tldp.org/LDP/abs/html/commandsub.html –

+3

这不是严格意义上正确的。该命令的结果是0(存储在$?中),该命令的**输出**是该文件的内容。 –

+1

我试过这个,现在得到上面的错误 – BluGeni

22

在bash $(< answer.txt)是一个内嵌 简写$(cat answer.txt)

我怀疑你正在运行此print

NAME 
    run-mailcap, see, edit, compose, print − execute programs via entries in the mailcap file 
+2

这不是一个简写。这是根据bash参考手册等同于faster_。这绝对是OP的答案。 (它应该是被接受的)。您还应该提及如何打印'$ file1'的扩展:'echo“$ file1”'。 –

+0

很好的发现错误信息真的意味着他输入了“print”而不是“printf”,这就是我带来的。 –

相关问题