【问题标题】:Set variable from content of files in bash(loop)从bash(循环)中的文件内容设置变量
【发布时间】:2018-12-17 11:39:50
【问题描述】:

我正在尝试将证书(刚刚创建)上传到某个存储。

所以我可以读取我文件夹中的所有证书,并希望将每个文件的内容用于循环中的变量。

#!/bin/bash
dir="${0%/*}"
#for f in $(cat $dir"/"*.crt)
#  do
#    data='{"certificate_data":'"$f"'}'
#done 
url="localhost:50183/api/v0.1/Certificates"
data='{"certificate_data":'$(cat $dir"/"*.crt)'}'
echo "$data"

所以我一次获得了所有证书,但我需要在 $data 中以正确的形式在循环中获取文件的每个内容,例如:

{"certificate_data":"<certificate_data_from_file>"}
{"certificate_data":"<certificate_data_from_file>"}
......
and so on

我知道我应该使用另一个循环,但不知道如何。

感谢任何提示!

【问题讨论】:

  • 旁注:$(cat file.txt) 可以替换为$(&lt; file.txt)
  • 不清楚您对这些信息做了什么,因为您的简单示例不断覆盖data。但也许在您的同一个 for 循环中,您将拥有 data_file='{"certificate_data":'"$f"'}' 然后 data_cert='{"certificate_data":'$(&lt; $dir"/"*.crt)'}' 后跟您想要对 $data_file$data_cert 执行的任何逻辑。
  • 好的,尝试删除for f in $(cat $dir"/"*.crt) do data='{"certificate_data":'"$f"'}' done,没有它也可以,但是将所有证书填写在 1 个“certificate_data”中,我需要将 1 个证书放入 1 个“certificate_data”
  • 更改两个数据分配有帮助吗? data="${data}{\"certificate_data\":....}"

标签: linux bash shell loops


【解决方案1】:

这应该可以完成工作:

#!/bin/bash
for f in ./dir/*.crt
do
  data='{"certificate_data":"'"$(< "${f}")"'"}'
  echo "${data}"
done

测试:

$ ls ./dir/*
./dir/cert1.crt  ./dir/cert2.crt
$ cat ./dir/*
I am certificate1.
I am certificate2.
$ ./cert.sh
{"certificate_data":"I am certificate1."}
{"certificate_data":"I am certificate2."}

【讨论】:

  • 本身不需要用变量污染内存。只需将魔术酱直接放在echo 参数中即可。
  • 我认为提问者想将它放在变量中,所以他可以做点什么?用它。 echo 这里只是测试用变量做某事。
  • 谢谢,应该可以,但不适合我。我尝试设置当前目录cwd=$(pwd) 然后for f in $cwd"/"*.crt 并且只获得1个证书数据。我需要将 *.crt 文件与其他文件分开,因为我的第一个脚本会为它们生成不同类型的证书和密钥,所以我只需要粘贴证书数据而不粘贴 *.key 文件中的数据。
  • 我将分析器编辑为仅获取 .crt,如果您想要当前目录中的所有 crts,请使用以下内容:for f in "$(pwd)/"*.crt 无论如何为了更安全的解决方案我宁愿使用查找 -exec 或 xargs -0 组合
  • 我能问一下为什么当我在循环后使用 echo "${data}" 时它只显示第二个(共 2 个)证书。但是当在循环中使用它时,它会显示 2 of 2?
猜你喜欢
  • 1970-01-01
  • 2019-01-09
  • 2014-03-02
  • 1970-01-01
  • 2010-12-04
  • 1970-01-01
  • 2011-06-02
  • 1970-01-01
相关资源
最近更新 更多