需要将文本文件的内容分配给bash脚本中的变量
我对制作bash脚本非常陌生,但我的目标是获取一个.txt文件,并将txt文件中的字符串指定给一个变量。我已经试过了(不知道我是否在正确的轨道上) 当我运行这个时,我会需要将文本文件的内容分配给bash脚本中的变量,bash,Bash,我对制作bash脚本非常陌生,但我的目标是获取一个.txt文件,并将txt文件中的字符串指定给一个变量。我已经试过了(不知道我是否在正确的轨道上) 当我运行这个时,我会 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" 我能做些什
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使用变量来执行此操作。您需要反勾号来捕获命令的输出(并且您可能希望
echo
而不是print
):
$()
构造从命令返回stdout
file_contents=$(cat answer.txt)
在bash中,$(
相当于$(cat answer.txt)
,但是内置的,因此更快更安全。看
我怀疑你在运行这个:
+1; 更具体地说,它被称为命令替换:严格来说,这不是真的。该命令的结果是0(存储在$?),该命令的输出是文件的内容。正如我在回答中所说,您使用的是print而不是echo。另外,您可能不需要
FILE=“answer.txt”
您没有在任何地方使用它。print
是Korn shell,如果使用Bash,您只能使用echo
(Korn shell也支持它)。它不是真正的速记。根据bash参考手册,它相当于更快的速度。这绝对是OP的答案(应该是公认的答案)。您还应该提到如何打印扩展的$file1
:echo“$file1”
。很好的发现,错误消息实际上意味着他键入了“print”而不是“printf”,这正是我来到这里的原因。这不是一个速记,而是一个内置的,因此,它避免了对cat的攻击,因此速度要快得多。这应该是公认的答案。完整的示例是file1=“$(
,因为这被标记为解决方案,请注意,建议的解决方案鼓励使用$(cat answer.txt)
,因为它不使用特殊字符,更具可读性和健壮性(例如,支持更多shell)。囊性纤维变性:
file1=`cat answer.txt`
echo $file1
file_contents=$(cat answer.txt)
NAME
run-mailcap, see, edit, compose, print − execute programs via entries in the mailcap file