问题描述
我正在尝试提高自己的脚本编写技能。
我知道有在线转换器正在执行此操作,但是如果.crt已经是.pem格式,并且不进行转换,我想制作一个在特定文件夹(/opt/Citrix/ICAClient/keystore/cacerts/
)中进行比较的脚本。 / p>
所以我知道这显然不是最好的方法...但是我已经开始这样了:
`
#!/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
”的内容(在will的for循环中,它将转换每个namefile.pem中的每个namefile.crt)。
如果有人可以帮助我,我将不胜感激...(是的,我已经尝试过在网上搜索,参加了一些在线课程,但没有人对bash的数组说同样的话,所以我有点迷路了...)
解决方法
我想要的是逐行存储结果的结果
然后这样做。
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
是useless use of cat。使用grep .. file
或< file grep ...
。
记住do not parse ls
output。不要ls | something
。优先选择球状或find
。
阅读how to read a stream line by line in bashfaq。阅读how to use arrays in bashfaq。
请注意,grep
解析了一个正则表达式,因此grep .pem
匹配任何字符,后跟pem
。我想您想要grep '\.pem'
。我认为grep -v "$Certificate_pem"
并没有达到您的预期效果-我想您是想使用comm
或join
从另一个列表中存在的一个换行符分隔的元素中过滤元素。 / p>
此数组将用于启动类似这样的东西“ 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
将带有换行符分隔列表的字符串存储到数组中(一定要了解how to store variables in a pipeline)。
mapfile -t Certificate_crt_WO_pem < <(something)