如果bash中不满足任何条件,则打印声明

时间:2018-07-16 14:38:13

标签: bash amazon-web-services aws-iam

我有一个bash脚本,用于确定某人的aws密钥是否早于90天。如果它们是脚本,则向他们发送一封电子邮件,其中包含有关如何旋转键的信息。

如果没有键的使用期限超过90天,我希望脚本打印一条语句,这样就不会发送电子邮件。

对于每个用户密钥,我有两个if独立的if语句:

if [ "$key1dtSec" -lt "$taSec" ]; then
    printf "%s created on %s\\nThis key is %s days old and needs to be replaced.\\nAn email will be sent." "$user_access_key1" "$key1_date_created." "$key1AgeDays"
    echo -e  "$template1" | /usr/bin/mail --append="Content-type: text/html" -s "AWS Key Rotation Needed for $user_name in $aws_key" "$email_address"
    echo; echo
fi

if [ "$key2dtSec" -lt "$taSec" ]; then
    printf "%s created on %s.\\nThis key is %s days old and needs to be replaced.\\nAn email will be sent." "$user_access_key2" "$key2_date_created"  "$key2AgeDays"
    echo -e  "$template2" | /usr/bin/mail --append="Content-type: text/html" -s "AWS Key Rotation Needed for $user_name in $aws_key" "$email_address"
    echo; echo
fi

key1dtSeckey2dtSec是aws键的寿命,以秒为单位。 taSec设置为90天之前。

如果我使用elif语句,并且两个键都只使用一个if / then语句,那么只有执行第一个if语句(该键可以告诉您密钥的使用期限超过90天)才会被执行。

我该怎么写呢?

  1. 如果第一个密钥的日期早于90天并且已发送电子邮件。
  2. 如果第二个密钥早于90天,则会发送一封电子邮件。
  3. 如果没有密钥的使用期限超过90天,则会显示一条消息,指出没有密钥的使用期限超过90天。

2 个答案:

答案 0 :(得分:2)

希望,我正确理解了您的问题。请检查下面的答案。

    key1=0
    key2=0

    if [ "$key1dtSec" -lt "$taSec" ]; then
        printf "%s created on %s\\nThis key is %s days old and needs to be replaced.\\nAn email will be sent." "$user_access_key1" "$key1_date_created." "$key1AgeDays"
        echo -e  "$template1" | /usr/bin/mail --append="Content-type: text/html" -s "AWS Key Rotation Needed for $user_name in $aws_key" "$email_address"
        echo; echo
        key1=1
       fi

     if [ "$key2dtSec" -lt "$taSec" ]; then
            printf "%s created on %s.\\nThis key is %s days old and needs to be replaced.\\nAn email will be sent." "$user_access_key2" "$key2_date_created"  "$key2AgeDays"
        echo -e  "$template2" | /usr/bin/mail --append="Content-type: text/html" -s "AWS Key Rotation Needed for $user_name in $aws_key" "$email_address"
        echo; echo
        key2=1
       fi

     if [  "$key1" -eq 0 && "$key2" -eq 0]; then 
        echo "no key is older than 90 days."
        fi

答案 1 :(得分:2)

如果我对你的理解正确,那么你的逻辑就像:

if condition1; then # first key
  action1 # send email
fi

if condition2; then # second key
  action2 # send different email
fi

if ! condition1 && ! condition2; then # neither key
  action3 # print something
fi

如果是这样,请将condition1替换为[ "$key1dtSec" -lt "$taSec" ],与condition2相同,然后在每个块中插入适当的操作。