Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

shell - 如何将文件读入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  

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”,它将输出以下内容:)

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?

(是否有捷径可寻?)

  ask by kaka translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In cross-platform, lowest-common-denominator sh you use:

(在跨平台的最小公分母sh您可以使用:)

#!/bin/sh
value=`cat config.txt`
echo "$value"

In bash or zsh , to read a whole file into a variable without invoking cat :

(在bashzsh ,无需调用cat即可将整个文件读入变量:)

#!/bin/bash
value=$(<config.txt)
echo "$value"

Invoking cat in bash or zsh to slurp a file would be considered a Useless Use of Cat .

(在bashzsh调用cat来处理文件将被视为Cat无用 。)

Note that it is not necessary to quote the command substitution to preserve newlines.

(请注意,不必引用命令替换来保留换行符。)

See: Bash Hacker's Wiki - Command substitution - Specialities .

(请参阅: Bash Hacker的Wiki-命令替代-Specialties 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...