[英]get each line of a command in an array bash raspbian
我正在努力提高我的脚本编写技能。 我知道有在线转换器正在这样做,但我想制作一个脚本来比较某个文件夹( /opt/Citrix/ICAClient/keystore/cacerts/
),如果.crt已经是.pem格式并且如果不转换它们。
所以我知道这显然不是最好的方法......但我已经开始这样了:
`
#!/bin/bash
#remove both files if they already exists
rm crt.txt
rm pem.txt
#certificate selection in .crt format
Certificate_crt=$(sudo ls /opt/Citrix/ICAClient/keystore/cacerts/ | grep .crt | sed 's/\(.*\)\..*/\1/')
#certificate selection in .pem format
Certificate_pem=$(sudo ls /opt/Citrix/ICAClient/keystore/cacerts/ | grep .pem | sed 's/\(.*\)\..*/\1/')
#sending results in text files
echo "$Certificate_crt" >> crt.txt
echo "$Certificate_pem" >> pem.txt
#recovery of certificate names in .crt not having a .pem equivalent
Certificate_crt_WO_pem=$(cat crt.txt | grep -v "$Certificate_pem" | tr " " "\n")
#echo "$Certificate_crt_WO_pem"
#initialisation
i=0
#Print the split string
for i in "${Certificate_crt_WO_pem[@]}"
do
name_certificate=$(echo $i | tr " " "\n")
echo "${name_certificate[@]}"
echo "$i"
i=i+1
done
`
问题是,当我的“for”启动时,它会将“Certificate_crt_WO_pem”的所有结果存储在数组 $name_certificate[0] 中,然后自行停止。
我想要的是逐行存储“ cat crt.txt | grep -v "$Certificate_pem" | tr " " "\n"
" 的结果到数组 name_certificate 中。
这个数组将用于启动类似这样的东西“ openssl -in $name_certificate[$i].crt -out $name_certificate[$i].pem PEM
”(在 for 循环中将转换每个 namefile.crt 在每个名称文件.pem)。
如果有人能帮助我,我将不胜感激......(是的,我已经尝试在 .net 上搜索,已经学习了一些在线课程,但他们都没有对 bash 的 arrays 说同样的话,所以我有点迷路...)
我想要的是逐行存储结果
然后那样做。
var=$(something)
# ^^ - normal variable assignment
var=( $(something) )
# ^^ ^ - array assignment
# the unquoted result of expansions is split on IFS
# default on tabs, newlines and spaces
所以我想你想要:
Certificate_crt_WO_pem=($(grep -v "$Certificate_pem" crt.txt))
做cat file | grep
cat file | grep
是cat 的无用使用。 使用grep.. file
或< file grep...
。
记住不要解析ls
output 。 不要ls | something
ls | something
。 更喜欢 globulation 或find
。
阅读如何在 bashfaq 中逐行读取 stream 。 阅读如何在 bashfaq 中使用 arrays 。
请注意, grep
解析正则表达式,因此grep.pem
匹配任何后跟pem
的字符。 我猜你想要grep '\.pem'
。 我不认为grep -v "$Certificate_pem"
做你认为它做的事 - 我猜你的意思是使用comm
或join
来过滤另一个列表中存在的换行符分隔的元素。
这个数组将用于启动类似这样的东西“openssl -in $name_certificate[$i].crt -out $name_certificate[$i].pem PEM”
最好的办法是不这样做,而是在数据出现时对其进行解析,而不是将它们存储在变量中。
# get all .crt fiels
find /opt/Citrix/ICAClient/keystore/cacerts/ -maxdepth 1 -mindepth 1 -type f -name '*.crt' |
# remove extension
sed 's/\.crt$//' |
# filter out files where .pem does exists already
while IFS= read -r file; do
if [[ -r "$file".pem ]]; then continue; fi
printf "%s\n" "$file"
done |
# execute openssl for the rest
xargs -d'\n' -i{} openssl -in {}.crt -out {}.pem PEM
但是,如果您愿意,可以使用mapfile
将带有换行符分隔列表的字符串存储到数组中(一定要了解如何在管道中存储变量)。
mapfile -t Certificate_crt_WO_pem < <(something)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.