如何将文件读入shell中的变量? [英] How to read a file into a variable in shell?
问题描述
我想读取一个文件并将其保存在变量中,但我需要保留该变量,而不仅仅是打印出文件.我怎样才能做到这一点?我已经写了这个脚本,但它不是我需要的:
I want to read a file and save it in variable, but I need to keep the variable and not just print out the file. How can I do this? I have written this script but it isn't quite what I needed:
#!/bin/sh
while read LINE
do
echo $LINE
done <$1
echo 11111-----------
echo $LINE
在我的脚本中,我可以给出文件名作为参数,因此,例如,如果文件包含aaaa",它会打印出来:
In my script, I can give the file name as a parameter, so, if the file contains "aaaa", for example, it would print out this:
aaaa
11111-----
但这只是将文件打印到屏幕上,我想将其保存到变量中!有没有简单的方法可以做到这一点?
But this just prints out the file onto the screen, and I want to save it into a variable! Is there an easy way to do this?
推荐答案
在跨平台、最低公分母 sh
中你使用:
In cross-platform, lowest-common-denominator sh
you use:
#!/bin/sh
value=`cat config.txt`
echo "$value"
在 bash
或 zsh
中,将整个文件读入一个变量而不调用 cat
:
In bash
or zsh
, to read a whole file into a variable without invoking cat
:
#!/bin/bash
value=$(<config.txt)
echo "$value"
在 bash
或 zsh
中调用 cat
来获取文件将被视为 猫的无用使用.
Invoking cat
in bash
or zsh
to slurp a file would be considered a Useless Use of Cat.
请注意,不必引用命令替换来保留换行符.
Note that it is not necessary to quote the command substitution to preserve newlines.
请参阅:Bash Hacker 的 Wiki - 命令替换 - 专业.
这篇关于如何将文件读入shell中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!