frodo
frodo

Reputation: 1063

How to include three "AND" conditions in bash script

Im trying to create three test conditions so that diretory and user and group account permisions are set on a directory - when I use the script below with -a to include the and conditions they are not picked up - If I do them individually they work - where am I going wrong ?

#!/bin/bash

if [ $(stat -c "%a" /wwwserver/virtual_hosts/www.test1.com) != "750"  -a  $(stat -c "%U" /wwwserver/virtual_hosts/www.test1.com) != "user"  -a  $(stat -c "%G" /wwwserver/virtual_hosts/www.test1.com) != "group" ] ;
 then echo -e "\n\nDirectory Permissions Changed\n" $(stat /wwwserver/virtual_hosts/www.test1.com) "\n" "\nChanging Permissions back to 750 user group\n" | mail -s " Directory Permissions Changed for www.test1.com" [email protected];
        chmod 750 /wwwserver/virtual_hosts/www.test1.com;
        chown -R user.group /wwwserver/virtual_hosts/www.test1.com;
fi

Upvotes: 0

Views: 504

Answers (2)

hek2mgl
hek2mgl

Reputation: 158020

Basically your scripts works, check:

touch "test1.com"
chmod 400 "test1.com"

if [ $(stat -c "%a" "test1.com") != "750" -a $(stat -c "%U" "test1.com") != "user" -a $(stat -c "%G" "test1.com") != "group" ]
then
    echo "do something ..."
fi

This outputs do something ....

It looks like one of the 3 conditions do indeed fail in your case. Meaning either file permissions are already 750 or ownership is already set to user or group ownership is set to group.


Btw, I strongly recommend to quote the command substitutions properly. This is because the output returned from that commands may contain problematic characters which would get interpreted by the shell otherwise. Care about quoting in any situation during shell scripting, regardless what output you may expect -> pigs can fly!

Here comes the example above - properly quoted:

touch "test1.com"
chmod 400 "test1.com"

if [ "$(stat -c "%a" "test1.com")" != "750" -a "$(stat -c "%U" "test1.com")" != "user" -a "$(stat -c "%G" "test1.com")" != "group" ]
then
    echo "do something ..."
fi

Upvotes: 2

anubhava
anubhava

Reputation: 785216

You can use multiple anded conditions like this:

s='abc'
n=4
m=5

[[ -n "$s" && $n > 3 && $m > 6 ]] && echo "all conditions passed"
all conditions passed

I.e. use [[...]] for all conditions and use && for anding.

Upvotes: 1

Related Questions