需要将文本文件的内容分配给bash脚本中的变量 [英] Need to assign the contents of a text file to a variable in a bash script
问题描述
我对制作bash脚本非常陌生,但是我的目标是获取我拥有的.txt文件,并将txt文件中的单词字符串分配给变量.我已经尝试过了(无论是否在正确的轨道上都不知道).
I am very new to making bash scripts, but my goal here is to take a .txt file I have and assign the string of words in the txt file to a variable. I have tried this (no clue if I am on the right track or not).
#!/bin/bash
FILE="answer.txt"
file1="cat answer.txt"
print $file1
运行此命令时,我会得到
When I run this, I get
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"
我该怎么做才能使这项工作成功?
What can I do to make this work?
编辑** 当我将其更改为:
Edit** When I change it to:
#!/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对该变量进行操作.
When I enter cat answer.txt it prints out this text string should be a varible like it should but, I still can't get the bash to do that with the varible.
推荐答案
您需要反引号以捕获命令的输出(并且您可能希望使用echo
而不是print
):
You need the backticks to capture output from a command (and you probably want echo
instead of print
):
file1=`cat answer.txt`
echo $file1
这篇关于需要将文本文件的内容分配给bash脚本中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!