Bash 检测if语句中的多个文件

Bash 检测if语句中的多个文件,bash,if-statement,Bash,If Statement,我编写了以下bash代码来检测SSL证书是否存在,如果存在,则跳过创建一个 我需要扩展检测到的文件的列表,以便其中任何文件的存在都将跳过SSL证书的创建 文件的完整列表是“trailes.cer”或“trailes.key”或“trailes.pem” 另一种方法是在检测后,提示用户是否要创建SSL证书 file="assets/certificates/trailers.cer" if [ -f "$file" ]; then echo 'SSL Certificates already cr

我编写了以下bash代码来检测SSL证书是否存在,如果存在,则跳过创建一个

我需要扩展检测到的文件的列表,以便其中任何文件的存在都将跳过SSL证书的创建

文件的完整列表是“trailes.cer”或“trailes.key”或“trailes.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

您可以使用多个
测试和
|
if
中设置多个条件,如下所示:

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
当文件较多时,使用数组会更容易、更可读,如下所示:

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

假设它足以退出整个脚本

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“/资产/证书/$file”

-o
已弃用;改为使用
test-f“$path1”| | test-f“$path2”| | test-f“$path3”
。它写在哪里?在我的最新Debian测试附带的bash中,
man test
help test
中都没有提到这一点。由于解析过程中根据使用的其他参数存在歧义,因此(请参阅应用程序使用部分)将其标记为过时。谢谢。此选项如何处理文件位于与当前工作目录不同的目录中?例如:资产/证书/挂车。谢谢