Bash不读取文件到变量

时间:2022-01-22 05:45:50

I have a simple bash script

我有一个简单的bash脚本

#!/bin/bash
TEXT=$(<"$(pwd)/data/test.json")
echo "$TEXT"

Which should read the whole file and assign it to a variable TEXT however, when I run it, the only output I get is a newline character. In the same directory, as the script is, I tried to run

它应该读取整个文件并将其分配给一个变量文本,但是,当我运行它时,我得到的唯一输出是一个换行字符。在与脚本相同的目录中,我尝试运行

cat "$(pwd)/data/test.json"

And it gives me the following output

它给了我以下的输出

{ "data": true }

Why is the bash script not working?

为什么bash脚本不能工作?

Edit:

编辑:

My bash version is GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)

我的bash版本是GNU bash,版本4.3.48(1)-release (x86_64-pc-linux-gnu)

3 个解决方案

#1


2  

How are you executing your script? Are you typing sh script.sh? Make sure you do ./script.sh so it executes with /bin/bash not /bin/sh.

你如何执行你的脚本?你在打字吗?一定要写。/脚本。所以它执行的是/bin/bash而不是/bin/ sh。

#2


0  

To read a file in a variable, you can simply use the cat command.

要读取变量中的文件,只需使用cat命令。

TEXT="$(cat $(pwd)/data/test.json)"

The double quotes ensure the newlines are kept

双引号确保保持换行

echo "$TEXT"

#3


0  

use "bash {scriptname}" or "./{scriptname}"

使用“bash {scriptname}”或“。/{scriptname}”

also, you don't have to cat or echo to get the var set: VAR=$(

同样,您不必使用cat或echo来获取var集合:var =$(

#1


2  

How are you executing your script? Are you typing sh script.sh? Make sure you do ./script.sh so it executes with /bin/bash not /bin/sh.

你如何执行你的脚本?你在打字吗?一定要写。/脚本。所以它执行的是/bin/bash而不是/bin/ sh。

#2


0  

To read a file in a variable, you can simply use the cat command.

要读取变量中的文件,只需使用cat命令。

TEXT="$(cat $(pwd)/data/test.json)"

The double quotes ensure the newlines are kept

双引号确保保持换行

echo "$TEXT"

#3


0  

use "bash {scriptname}" or "./{scriptname}"

使用“bash {scriptname}”或“。/{scriptname}”

also, you don't have to cat or echo to get the var set: VAR=$(

同样,您不必使用cat或echo来获取var集合:var =$(