简体   繁体   中英

Performing IF Statement in awk

I have an array of users and I need to see if the owner of a file (logfile.log) exists within the array. Using awk I am able to pull the owner ($3) but when I use try to see if $3 is in user I get a syntax error at the beginning of my if statement. My limited understanding is that awk is not liking the syntax.

user=('michael' 'mark' 'luke' 'john' 'phil' 'sam' 'kevin'); 
ls -ldL logfile.log 2>/dev/null | 
/bin/awk '{ 
    Result = $NF ":\tPermissions=" $1; 
    if ([[ "${user[*]}" =~ (^|[^[:alpha:]])$3([^[:alpha:]]|$) ]]) { 
        Result = Result "\tOwner=SUPPORT"; 
    } 
    else { 
        Result = Result "\tOwner=" $3; 
    } 
    print Result;
}'

Don't parse ls ( http://mywiki.wooledge.org/ParsingLs ). Use stat to get the owner (check your stat man page, there are different implementations of different OS's)

# give your arrays a plural variable name
users=('michael' 'mark' 'luke' 'john' 'phil' 'sam' 'kevin')
owner=$(stat -c '%U' logfile.log)

if [[ " ${users[*]} " == *" $owner "* ]]; then    # spaces are deliberate
    echo logfile.log has a valid owner: $owner
else
    echo logfile.log is not owned by a valid user: $owner
fi

The other approach is to iterate over the array and look for an exact match:

valid=false
for user in "${users[@]}"; do
    if [[ $user == $owner ]]; then
        valid=true
        break
    fi
done
if $valid; then
    echo file has a valid owner
fi

The main problem in your code is that you expect awk to understand bash syntax. It doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM