我编写了以下bash代码来检测SSL证书是否存在,如果存在,则跳过创建一个。
我需要扩展检测到的文件列表,这样任何文件都会跳过SSL证书的创建。
完整的文件列表是“trailers.cer”或“trailers.key”或“trailers.pem”
检测后的方法是提示用户询问是否要创建SSL证书
file="assets/certificates/trailers.cer"
if [ -f "$file" ]; then
echo 'SSL Certificates already created'
else
openssl req -new -nodes -newkey rsa:2048 -out ./assets/certificates/trailers.pem -keyout ./assets/certificates/trailers.key -x509 -days 7300 -subj "/C=US/CN=trailers.apple.com"
openssl x509 -in ./assets/certificates/trailers.pem -outform der -out ./assets/certificates/trailers.cer && cat ./assets/certificates/trailers.key >> ./assets/certificates/trailers.pem
fi
答案 0 :(得分:2)
假设退出整个脚本就足够了,
for file in trailers.cer trailers.key /assets/certificates/trailers.pem; do
test -f "$file" && exit 1 # or even 0?
done
# If you reach through here, none existed
我将其中一个项目更改为绝对路径,以显示它是如何完成的。如果所有文件的路径相同,则可以重构以后提供路径; test -f "/assets/certificates/$file"
答案 1 :(得分:1)
您可以在if
中使用多个test
和||
添加多个条件,如下所示:
if test -f "$path1" || test -f "$path2" || test -f "$path3"; then
...
fi
当文件很多时,使用数组可以更容易和更易读,如下所示:
#!/bin/bash
basedir=assets/certificates
files=(trailers.cer trailers.key trailers.pem)
found=
for file in ${files[@]}; do
path="$basedir/$file"
if [ -f "$path" ]; then
echo SSL Certificates already created
found=1
break
fi
done
if test ! "$found"; then
openssl req -new -nodes -newkey rsa:2048 -out ./assets/certificates/trailers.pem -keyout ./assets/certificates/trailers.key -x509 -days 7300 -subj "/C=US/CN=trailers.apple.com"
openssl x509 -in ./assets/certificates/trailers.pem -outform der -out ./assets/certificates/trailers.cer && cat ./assets/certificates/trailers.key >> ./assets/certificates/trailers.pem
fi