我想读取一个文件并将其保存在变量中,但我需要保留变量而不仅仅是打印出文件。
我该怎么做呢?我已经写了这个脚本,但它不是我所需要的:
#!/bin/sh
while read LINE
do
echo $LINE
done <$1
echo 11111-----------
echo $LINE
在我的脚本中,我可以将文件名作为参数,因此,如果文件包含“aaaa”,例如,它将打印出以下内容:
aaaa
11111-----
但这只是将文件打印到屏幕上,我想将它保存到一个变量中!
有什么简单的方法吗?
正如Ciro Santilli指出的,使用命令替换将删除尾随换行符。他们添加尾随字符的变通方法很棒,但在使用了相当长的一段时间后,我决定需要一个根本不使用命令替换的解决方案。
我的方法现在使用read和printf内置的-v标志,以便将stdin的内容直接读入一个变量。
# Reads stdin into a variable, accounting for trailing newlines. Avoids
# needing a subshell or command substitution.
# Note that NUL bytes are still unsupported, as Bash variables don't allow NULs.
# See https://stackoverflow.com/a/22607352/113632
read_input() {
# Use unusual variable names to avoid colliding with a variable name
# the user might pass in (notably "contents")
: "${1:?Must provide a variable to read into}"
if [[ "$1" == '_line' || "$1" == '_contents' ]]; then
echo "Cannot store contents to $1, use a different name." >&2
return 1
fi
local _line _contents=()
while IFS='' read -r _line; do
_contents+=("$_line"$'\n')
done
# include $_line once more to capture any content after the last newline
printf -v "$1" '%s' "${_contents[@]}" "$_line"
}
它支持带或不带换行符的输入。
使用示例:
$ read_input file_contents < /tmp/file
# $file_contents now contains the contents of /tmp/file