Shell/Bash-如何将数组保存到文件中并加载另一个文件数组? [英] Shell/Bash - How to save array to file and another file array load?

查看:76
本文介绍了Shell/Bash-如何将数组保存到文件中并加载另一个文件数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数组保存到文件并加载另一个文件数组?

How to save array to file and another file array load?

file1.sh
ARR=("aaa" "bbb" "ccc");
save to file2; # I do not know how :-(

file3.sh
load from file2; # I do not know how :-(
echo ${ARR[@]};

我尝试过...

file1.sh
declare -a ARR > /tmp/file2

file3.sh
source /tmp/file2
echo ${ARR[@]};

不起作用:-(请教别人更好的方法?谢谢...

does not work :-( Advise someone better way? Thank you...

推荐答案

如果变量的值不在多行中,则一种基本且简单的方法是使用set:

If the values of your variables are not in multiple lines, a basic and easy way for it is to use set:

# Save
set | grep ^ARR= > somefile.arrays
# Load
. somefile.arrays

但是,当然,如果您对安全性有某种了解,还有其他解决方案,但这是最快的方法.

But of course if you're somehow security sensitive there are other solutions but that's the quickest way to do it.

更新多行数组:

# Save
printf "%s\x00" "${ARR[@]}" > somefile.arrays
# Load
ARR=() I=0
while read -r ARR[I++] -d $'\0'; do continue; done < somefile.arrays

如果您的值上没有任何地方 $'\ 0',则该方法有效.如果是这样,则可以使用除 $'\ 0'之外的其他唯一分隔符.只需相应地更改 \ x00 $'\ 0 .

That would work if your values doesn't have $'\0' anywhere on them. If they do, you can use other delimeters than $'\0' that are unique. Just change \x00 and $'\0 accordingly.

这篇关于Shell/Bash-如何将数组保存到文件中并加载另一个文件数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆