我对制作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时,它打印出来的文本字符串应该是应该的变量,但是,我仍然无法通过varible来获取bash。
答案 0 :(得分:42)
在bash中$(< answer.txt)
是内置的
$(cat answer.txt)
我怀疑你正在运行此print
:
NAME
run-mailcap, see, edit, compose, print − execute programs via entries in the mailcap file
答案 1 :(得分:31)
你需要反引号来捕获命令的输出(你可能想要echo
而不是print
):
file1=`cat answer.txt`
echo $file1
答案 2 :(得分:19)
$()
构造从命令返回stdout
。
file_contents=$(cat answer.txt)