需要将文本文件的内容分配给bash脚本中的变量

Blu*_*eni 23 bash

我是制作bash脚本的新手,但我的目标是获取一个.txt文件,并将txt文件中的字符串分配给变量.我试过这个(如果我在正确的轨道上没有线索).

#!/bin/bash
FILE="answer.txt"
file1="cat answer.txt"
print $file1
Run Code Online (Sandbox Code Playgroud)

当我跑这个时,我明白了

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"
Run Code Online (Sandbox Code Playgroud)

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

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

#!/bin/bash
    FILE="answer.txt"
    file1=$(cat answer.txt)
    print $file1
Run Code Online (Sandbox Code Playgroud)

我得到了这个:

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."
Run Code Online (Sandbox Code Playgroud)

当我输入cat answer.txt它打印出来时,这个文本字符串应该像它应该的变量但是,我仍然无法通过变量获得bash.

gle*_*man 45

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

我怀疑你是在运行这个print:

NAME  
    run-mailcap, see, edit, compose, print ? execute programs via entries in the mailcap file
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个简写.根据bash参考手册_equivalent by faster_.这绝对是OP的答案.(应该是公认的).你还应该提一下如何打印`$ file1`的扩展:`echo"$ file1"`. (5认同)
  • 完整的示例是 `file1="$(&lt;answer.txt)"` (3认同)
  • 这不是一个简写,而是一个内置的,因此,它避免了对 cat 的攻击,因此速度要快得多。这应该是公认的答案。 (2认同)

Jef*_*ald 43

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

file1=`cat answer.txt`
echo $file1
Run Code Online (Sandbox Code Playgroud)

  • 由于这被标记为解决方案,请注意,与建议的解决方案相比,鼓励使用“$(cat answer.txt)”,因为它无需特殊字符即可工作,更具可读性和健壮性(例如支持更多 shell)。比照:/sf/answers/329599861/ (8认同)

har*_*rpo 24

该$()建筑返回stdout从命令.

file_contents=$(cat answer.txt)
Run Code Online (Sandbox Code Playgroud)

  • 严格来说,这并不是真的.该命令的结果为0(存储在$?中),此命令的**输出**是文件的内容. (4认同)
  • +1; 更具体地说,它被称为命令替换:http://tldp.org/LDP/abs/html/commandsub.html (2认同)